C++ 使用运算符重载转换模板

标签 c++ templates

我有一个模板类,我尝试通过运算符重载将模板版本转换为另一个版本

enum MyTypes {A,B,C}

template<MyTypes T>
MyClass {
    const static MyType type_ = T;
    template<MyTypes U>       
    MyClass<U> convert(MyTypes t) {
        MyType<U> ret = MyType<U>();
        ....
        return r;
    }
    template<MyTypes U>      
    MyClass<U> operator()() {
        return convert(U);
    }
}

但是,这会产生(在 gcc、c11 上)

conversion from MyClass<0u> to non-scalar type MyClass<1u> requested

删除模板函数并尝试

MyClass<A> operator()() {
    MyClass<A> a = MyClass<A>();
    ...
    return a;
}

抛出

the error operator cannot be overloaded

基本上,我想要实现的是,如果我有

MyClass<A> a = MyClass<A>;
MyClass<B> b = a;

它根据 a 和转换创建了一个新的 MyClass。知道我的错误是什么吗?

编辑: 我扔掉了一个模板函数,只留下运算符

template<MyTypes U>      
MyClass<U> operator()() {
    MyClass<U> ret = MyClass<U>();
    ...
    return ret;
}

但这仍然产生

conversion from MyClass<0u> to non-scalar type MyClass<1u> requested

尝试做的时候

MyClass<B> = a

最佳答案

以下转换值并允许赋值:

#include <iostream>
#include <string>

enum MyTypes { A, B, C };

template<MyTypes T>
struct MyClass{
    const static MyTypes type_ = T;
    std::string history{"started as " + std::to_string(T)};

    template<MyTypes U>
    operator MyClass<U> () {
        return {history+" then became " + std::to_string(U)};
    }
};

int main()
{
    MyClass<A> a;
    MyClass<B> b = a;
    MyClass<C> c = b;

    std::cout << a.history << '\n';
    std::cout << b.history << '\n';
    std::cout << c.history << '\n';
}

输出:

started as 0
started as 0 then became 1
started as 0 then became 1 then became 2

关于C++ 使用运算符重载转换模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46596671/

相关文章:

javascript - 从 C++ 向网站发送数据

c++ - QWebPage 和多线程

c++ - 无限模板实例化

c++ - 带有方法参数的元编程

c++ - std::is_base_of 用于模板类

c++ - 自动将类成员注册到 C++ 中的包含对象

c++ - if 语句后跟 return 0

c++ - 当使用 malloc 而不是 new 时,类成员会发生什么情况?

C++ getline() 不需要命名空间声明

c# - 在控制台应用程序中将 HTML 标记传递到 RazorEngine