How do I explicitly instantiate a template function?
[EDIT 2]: Note that there was some confusion regarding the code in the original question due to code formatting issues. See AnthonyHatchkins' answer for more details.
If you really want to instantiate (instead of specialize or something) the function, do this:
template <typename T> void func(T param) {} // definition
template void func<int>(int param); // explicit instantiation.
[EDIT] There seems to be (a lot) of confusion regarding explicit instantiation and specialization. The code I posted above deals with explicit instantiation. The syntax for specialization is different. Here is syntax for specialization:
template <typename T> void func(T param) {} // definition
template <> void func<int>(int param) {} // specialization
Note that angle brackets after template!
Your code is correct.
The error message pertains to a place in the code that you didn't quote here.
Update:
Original code was
template <class T> int function_name(T a) {}
template int function_name<int>(int);
and it was correct.
But it was not quoted and thus looked like this:
template int function_name(T a) {}
template int function_name(int);
It generates the following error
a.cpp:1: error: explicit instantiation of non-template ‘int function_name’
a.cpp:1: error: expected `;' before ‘(’ token
a.cpp:3: error: ‘function_name’ is not a template function
which is clearly different from what OP cited.
In this variant the second line is ok (<int>
can be omitted here), but the first line is faulty. The compiler cannot guess that T
is a template parameter.
This may be helpful for instantiation template method when we want to split cpp/hpp file.
// foo.hpp
struct Foo
{
template<typename T>
void myMethod(T var);
};
// foo.cpp
#include <typeinfo>
#include <iostream>
template void Foo::myMethod(int var);
template void Foo::myMethod(double var);
template <typename T>
void Foo::myMethod(T var)
{
std::cout << typeid(T).name() << " - " << var << std::endl;
}
Example:
Foo foo;
foo.myMethod(1);
foo.myMethod(2.0);
// undefined reference to `void Foo::myMethod(float)'
// foo.myMethod(2.0F); <-- doesn't work as we don't have definition
OUT:
i - 1
d - 2
You can play it here: https://onlinegdb.com/gwAjMF9QH