c++ - 模板类中的通用模板指针

标签 c++ class templates pointers

我有一个模板类,它有一个指向同一类的指针(但不一定使用相同的类型)。这是一个例子:

template<class T>
class Foo{
    Foo(){}
    Foo* a;
    template<class U>
    void bar(Foo<U>* b){a=b;}
}

当我在主函数中使用它时,一切似乎都正常,直到我为参数使用不同的模板。

int main(){
    Foo<double> f1;
    Foo<double> f2;
    f1.bar(&f1);// no Errors

    Foo<bool> f3;
    Foo<double> f4;
    f3.bar(&f4);//Error : cannot convert 'Foo<double>*' to 'Foo<bool>*'
}

我是否可以在类 Foo 中定义一个指针,该指针有一个指向同一类的“通用”指针?

最佳答案

Is there anyway I can define a pointer in class Foo that has a "generic" pointer to the same class in it?

你所拥有的是正确的。您所期望看到的内容可能是建立在误解之上的。

Foo<bool>Foo<double>是完全不同的类(class)。类型/类模板允许您使用编译器生成新类型,但它们本身不是类。

如果您必须手动生成类,您将:

class Foo_bool{
    Foo_bool(){}
    Foo_bool* a;

    ...
};

class Foo_double{
    Foo_double(){}
    Foo_double* a;

    ...
};

这样,就很容易明白为什么不能使用:

Foo_bool a;
Foo_double b;
a.a = &b;   // Not allowed

这与使用没有什么不同:

Foo<bool> a;
Foo<double> b;
a.a = &b;   // Not allowed

最接近实现目标的方法是:

  1. Foo 的所有实例创建基类.
  2. 存储指向基类的指针。

演示该概念的简单程序:

class FooBase
{
   public:
      virtual ~FooBase() {}
};

template<class T>
class Foo : public FooBase {
   public:
    Foo(){}
    template<class U>
    void bar(Foo<U>* b){a=b;}

   private:
    FooBase* a; // Note the change. This is not Foo* any longer.
};

int main()
{
   Foo<bool> a;
   Foo<double> b;
   a.bar(&b);
}

关于c++ - 模板类中的通用模板指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891625/

相关文章:

class - 函数参数中的类(Arduino)无法编译

c++ - 在类中初始化时 C++ 中奇怪且不正确的数组大小行为

c++ - 在 C++ 中扩展数组的问题

templates - Backbone /Marionette 将 HTML 附加到区域中

c++ - 通用工厂设计模式的实现

c++ - boost asio 类似信号量的解决方案

c++ - 为什么 std::string 在 C++11 中没有 const char* 转换运算符?

C++ 操作结构的原始数据

c++ - undefined reference (模板)

c++ - C++中对象的多维数组