简体   繁体   English

具有默认构造函数的模板类中的模板化转换运算符?

[英]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这会导致以下情况发生:

  1. 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
  2. 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
  3. operator T<int> will be called on the aforementioned return value which will return a C<int> 将在上述返回值上调用operator T<int> ,该返回值将返回C<int>
  4. That return value which is a C<int> will attempt to be converted to an int which will call operator T<int> .... 该返回值是一个C<int>将尝试被转换为int它将调用operator T<int> ....
  5. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM