I want a templated class with a templated conversion operator and a default constructor, but my initial attempt isn’t working.
template<typename T>
class C
{
public:
C() {}
template<typename U>
operator U()
{
C<U> c; // (*)
c._a = dynamic_cast<U*>(_a);
return c;
}
private:
T* _a;
};
But now, when I try to create an instance of C,
template<typename T>
void F()
{
...
C<T> obj;
}
operator U() keeps calling itself over and over at (*), eventually segfaulting. The same thing happens when I define the function that does the casting externally and call it from operator U()–in which case there is no call to C::C() from within the class definition.
It seems to me then that the conversion operator is getting called when I want the default constructor called–it is essentially trying to convert itself. But surely, there’s a way to do what I’m trying to do?
Note that in
operator X(whereXis a type) functions, you should usually return something of typeX. You’re returning aC<U>when you’re trying to convert the invoking object to aUwhich causes the following to happen:int a = someC;(wheresomeCis aCof any type) will try to assign aC<X>to anintoperator T<int>will be called onsomeCwhich will return aC<int>and then try to assign it to anintoperator T<int>will be called on the aforementioned return value which will return aC<int>C<int>will attempt to be converted to anintwhich will calloperator T<int>….goto 3;Hopefully you can see why the infinite recursion and subsequent stack overflow occurs.
You cannot return a
C<U>fromoperator T<U>of classC. You need to redesign your class if you need to for some reason.