带有运算符重载的C ++转换模板

时间:2017-10-06 00:36:25

标签: 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

1 个答案:

答案 0 :(得分:1)

以下转换值并允许分配:

#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