Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiation of template member function

Tags:

c++

templates

In Class.h:

class Class {
public:
    template <typename T> void function(T value);
};

In Class.cpp:

template<typename T> void Class::function(T value) {
    // do sth
}

In main.cpp:

#include "Class.h"

int main(int argc, char ** argv) {
    Class a;
    a.function(1);
    return 0;
}

I get a linked error because Class.cpp never instantiate void Class::function<int>(T). You can explicitly instantiate a template class with :

template class std::vector<int>;

How do you explicitly instantiate a template member of a non-template class ?

Thanks,

like image 628
TiMoch Avatar asked Apr 12 '13 14:04

TiMoch


People also ask

How do I instantiate a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.

How many times is the template class instantiation?

cpp, there are two instantiations: template class B<int> and B<float>.

Why we need to instantiate the template?

In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.


2 Answers

You can use the following syntax in Class.cpp:

template void Class::function(int);

The template argument can be omitted because of type deduction, which works for function templates. Thus, the above is equivalent to the following, just more concise:

template void Class::function<int>(int);

Notice, that it is not necessary to specify the names of the function parameters - they are not part of a function's (or function template's) signature.

like image 60
Andy Prowl Avatar answered Oct 18 '22 18:10

Andy Prowl


Have you tried with the following in Class.cpp?

template void Class::function<int>(int value);
like image 40
Didier Trosset Avatar answered Oct 18 '22 20:10

Didier Trosset