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,
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.
cpp, there are two instantiations: template class B<int> and B<float>.
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).
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.
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.
Have you tried with the following in Class.cpp
?
template void Class::function<int>(int value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With