How to create a template function within a class? (C++)

C++TemplatesFunctionClass

C++ Problem Overview


I know it's possible to make a template function:

template<typename T>
void DoSomeThing(T x){}

and it's possible to make a template class:

template<typename T>
class Object
{
public:
    int x;
};

but is it possible to make a class not within a template, and then make a function in that class a template? Ie:

//I have no idea if this is right, this is just how I think it would look
class Object
{
public:
    template<class T>
    void DoX(){}
};

or something to the extent, where the class is not part of a template, but the function is?

C++ Solutions


Solution 1 - C++

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

Solution 2 - C++

See here: http://www.cs.otago.ac.nz/postgrads/alexis/tutorial/node39.html">Templates</a>;, http://www.cs.otago.ac.nz/postgrads/alexis/tutorial/node42.html">template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void	Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

Solution 3 - C++

Yes, template member functions are perfectly legal and useful on numerous occasions.

The only caveat is that template member functions cannot be virtual.

Solution 4 - C++

The easiest way is to put the declaration and definition in the same file, but it may cause over-sized excutable file. E.g.

class Foo
{
public:
template <typename T> void some_method(T t) {//...}
}

Also, it is possible to put template definition in the separate files, i.e. to put them in .cpp and .h files. All you need to do is to explicitly include the template instantiation to the .cpp files. E.g.

// .h file
class Foo
{
public:
template <typename T> void some_method(T t);
}

// .cpp file
//...
template <typename T> void Foo::some_method(T t) 
{//...}
//...

template void Foo::some_method<int>(int);
template void Foo::some_method<double>(double);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser98188View Question on Stackoverflow
Solution 1 - C++Not SureView Answer on Stackoverflow
Solution 2 - C++noneView Answer on Stackoverflow
Solution 3 - C++TobiasView Answer on Stackoverflow
Solution 4 - C++heyView Answer on Stackoverflow