模板函数中的通用模板参数

bse*_*lla 4 c++ templates pointers class function

我有一个模板类,它有一个-template-函数,它接受与第一个参数相同的类的指针,例如:

template<class T>
class Foo{
    void f(Foo* foo){}
}
Run Code Online (Sandbox Code Playgroud)

当我在我的main函数中使用它时,一切似乎都在工作,直到我为参数使用不同的模板.

int main(){
    Foo<double> f1;
    Foo<double> f2;
    f1.f(&f2); //No errors;

    Foo<bool> f3;
    f1.f(&f3);//Error : No matching function to call to Foo<double>::f(Foo<bool>*&)
}
Run Code Online (Sandbox Code Playgroud)

显然,这里定义的唯一功能是 Foo<T>::f(Foo<T>*)

有没有什么方法可以定义f采用"通用"模板Foo指针,以便我可以使用任何其他类型?

Vit*_*meo 11

使用自身Foo定义中的符号Foo相当于说Foo<T>.如果要支持任何其他实例化Foo,请创建f模板函数:

template <class T>
class Foo {
    template <class U>
    void f(Foo<U>* foo) { }
};
Run Code Online (Sandbox Code Playgroud)

  • @Elirovi:这是一个单独的问题.这个指针是否是一个成员变量?在这种情况下,Foo需要派生自FooBase,指针指向FooBase.它是局部变量吗?在这种情况下,你需要把它指向你指向的任何Foo指针. (2认同)