我有一个模板类,它有一个指向同一类的指针(但不一定使用相同的类型)。这是一个例子:
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
最接近实现目标的方法是:
- 为
Foo
的所有实例创建基类. - 存储指向基类的指针。
演示该概念的简单程序:
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/