[英]Templated conversion operator in a template class with default constructor?
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, 但是现在,当我尝试创建C的实例时,
template<typename T>
void F()
{
...
C<T> obj;
}
operator U() keeps calling itself over and over at (*), eventually segfaulting. 运算符U()不断在(*)上反复调用自身,最终进行段错误处理。 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.
当我定义从外部进行转换并从运算符U()进行调用的函数时,会发生相同的事情-在这种情况下,类定义中没有对C :: C()的调用。
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
(where X
is a type) functions, you should usually return something of type X
. 请注意,在
operator X
(其中X
是类型)中,通常应返回X
类型的东西。 You're returning a C<U>
when you're trying to convert the invoking object to a U
which causes the following to happen: 你返回
C<U>
当你试图调用对象转换为U
这会导致以下情况发生:
int a = someC;
(where someC
is a C
of any type) will try to assign a C<X>
to an int
someC
是任何类型的C
)将尝试将C<X>
分配给int
operator T<int>
will be called on someC
which will return a C<int>
and then try to assign it to an int
operator T<int>
将在someC
上调用,这将返回C<int>
,然后尝试将其分配给int
operator T<int>
will be called on the aforementioned return value which will return a C<int>
operator T<int>
,该返回值将返回C<int>
C<int>
will attempt to be converted to an int
which will call operator T<int>
.... C<int>
将尝试被转换为int
它将调用operator T<int>
.... goto 3;
Hopefully you can see why the infinite recursion and subsequent stack overflow occurs. 希望您能看到为什么发生无限递归和随后的堆栈溢出的情况。
You cannot return a C<U>
from operator T<U>
of class C
. 您不能从类
C
operator T<U>
返回C<U>
。 You need to redesign your class if you need to for some reason. 如果出于某种原因,您需要重新设计班级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.