Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning template types from non-template parameterized methods

Tags:

c++

templates

To define a templated class, I consider three different files. The declaration is in a .h file, the methods implentations are in a .cpp file, and explicit instantiations are included in a .inc file (by adding a line at the end of the .cpp, e.g: #include "bar-impl.inc").

Now, here's my problem. I've two template classes, say: Foo<S> and Bar<T>. Inside of the Bar<T> class, I've a method that returns a template Type FooType* ( which with my explicit instantiation I would like it to be, for example, Foo<float>*)

template<class T>
class Bar{
 ....
 template <class FooType>
 FooType* doSomething(int);
 ....
};

Since the compiler does not know what FooType* is, I tried to explicitly instantiated the doSomething method in the bar-impl.inc file.

//bar-impl.inc
template class Foo<float> * Bar<float>::doSomething(int);

However, it didn't work and I get an error of: no matching function for call to ‘Bar<float>::doSomething(int&)’ make: *** [main] Error 1

Does anybody knows if it's possible to do that?

like image 429
Javier Avatar asked Nov 14 '22 05:11

Javier


1 Answers

Methods templates work exactly the same way as function templates. You need to explicitly instantiate them upon use unless the template parameters can be derived from the call.

So you don't really need to make a specialization, what you need to do is specify the FooType upon use:

Bar<float> somevar; somevar.doSomething< Foo<float> >(somevalue);

If you always want to return Foo<T>* then just use Foo<T>* doSomething(int);

like image 67
Šimon Tóth Avatar answered Dec 19 '22 03:12

Šimon Tóth