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

问题描述 投票:4回答:1

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

template<class T>
class Foo{
    void f(Foo* foo){}
}

当我在我的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>*&)
}

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

有没有办法我可以定义f采用“通用”模板Foo指针,以便我可以使用任何其他类型?

c++ function class templates pointers
1个回答
11
投票

Foo本身的定义中使用符号Foo相当于说Foo<T>。如果你想支持Foo的任何其他实例化,请使f成为模板函数:

template <class T>
class Foo {
    template <class U>
    void f(Foo<U>* foo) { }
};
© www.soinside.com 2019 - 2024. All rights reserved.