Reputation: 4253
I have a template class where I try to convert a template verision to another via operator overload
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);
}
}
However, this yields (on gcc, c11)
conversion from MyClass<0u> to non-scalar type MyClass<1u> requested
removing the template functions and trying
MyClass<A> operator()() {
MyClass<A> a = MyClass<A>();
...
return a;
}
throws
the error operator cannot be overloaded
Basically, what I am trying to achieve is that if I have
MyClass<A> a = MyClass<A>;
MyClass<B> b = a;
that it creates a new MyClass based on a and the conversion. Any idea what my mistake here is?
EDIT: I tossed out one template function, just leaving the operator
template<MyTypes U>
MyClass<U> operator()() {
MyClass<U> ret = MyClass<U>();
...
return ret;
}
but this still yields
conversion from MyClass<0u> to non-scalar type MyClass<1u> requested
when trying to do
MyClass<B> = a
Upvotes: 0
Views: 178
Reputation: 11002
The following converts the value and allows for the assignment:
#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';
}
Output:
started as 0
started as 0 then became 1
started as 0 then became 1 then became 2
Upvotes: 2