Consider the following header and source files:
// main.cpp
#include "myClass.h"
int main()
{
MyClass m;
m.foo<double>();
m.foo<float>();
}
// myClass.h
#pragma once
#include <iostream>
using namespace std;
class MyClass
{
public:
template <typename T>
void foo()
{
cout << "Template function<T> called" << endl;
}
template <>
void foo<int>()
{
cout << "Template function<int> called" << endl;
}
template <>
void foo<float>();
};
// myClass.cpp
#include "myClass.h"
template <>
void MyClass::foo<float>()
{
cout << "Template function<float> called" << endl;
}
I get a linking error wrt the foo<float>
specialization. If I place the definition of the specialization in the header file, then everything works as expected.
I figured that the reason may be that the method is not explicitly instantiated (although full specialization of template class
does not need an explicit instantiation for proper linking). If I try to explicitly instantiate the method, I get this error:
error C3416: 'MyClass::foo' : an explicit specialization may not be explicitly instantiated
So the questions are:
- Is there any way to define the specialization in the
cpp
file and link properly? - If not, why not? I can explicitly instantiate template methods that are not specialized just fine. Why not the same for full specializations?
template function
specializations but not when the class is a non-template (does that matter?) and thetemplate method
is a full specialization. – Samaursafull
specialization of atemplate method
. – Samaursa