Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic template argument in template function

I have a template class which has a -template- function that takes a pointer of the same class as the first argument, for example:

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

When I use it in my main function, everything seems to be working until I use a different template for the argument.

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>*&)
}

Apparently, the only function defined here is Foo<T>::f(Foo<T>*)

Is there any way I can define f that takes a "generic" template Foo pointer so I can use it with any other type?

like image 971
bamia Avatar asked Dec 19 '22 02:12

bamia


1 Answers

Using the symbol Foo inside the definition of Foo itself is equivalent to saying Foo<T>. If you want to support any other instantiation of Foo, make f a template function:

template <class T>
class Foo {
    template <class U>
    void f(Foo<U>* foo) { }
};
like image 175
Vittorio Romeo Avatar answered Dec 24 '22 00:12

Vittorio Romeo