Functions.h:
#pragma once
#include <iostream>
template<class T> void TemplatedFunction(T* p) {}
template<> void TemplatedFunction<float>(float* p) {}
template<> void TemplatedFunction<char>(char* p) {}
Functions.cpp:
#include "Functions.h"
void Test()
{
TemplatedFunction<float>(NULL);
TemplatedFunction<char>(NULL);
}
main.cpp:
#include "Functions.h"
void Test();
int main()
{
Test();
return 0;
}
Build errors:
main.obj : error LNK2005: "void __cdecl TemplatedFunction<float>(float *)" (??$TemplatedFunction@M@@YAXPAM@Z) already defined in Functions.obj
main.obj : error LNK2005: "void __cdecl TemplatedFunction<char>(char *)" (??$TemplatedFunction@D@@YAXPAD@Z) already defined in Functions.obj
I know two ways to fix this:
Don't include Functions.h to several .cpp files - cannot be applied in complicated project, if h-file contains some additional definitions needed in many .cpp files.
Declare all templated functions as
static
. But this means that specialized functions appear in all .cpp files where Functions.h is included, even if they are not used, which possibly causes code duplication.
So, I see that specialized templated function behaves like non-templated function. Is there any other solution to prevent linker error without static
declaration? If functions are declared static
, does modern C++ compiler remove them from optimized build, if they are not used?
Edit.
After reading first two answers: I don't ask here how to prevent such linker error. Assuming that I cannot move specialization to .cpp file and leave it in .h file with static
or inline
, does this cause code duplication and bloating in optimized build, when these functions are added to every .cpp file where .h file is included, even if they are not used?