Question

I've got following class and template function:

template <size_t num>
class String{
 public:
  char charArray[num];
};

template <size_t num,typename T>
void getString(String<num> & string,T number){
 cout <<string.charArray<<' '<<number<<'\n';
}

then I tried to do an explicit instantiation as following to export that instantiation to a DLL but found out at last that it didn't get instantiated at all since I got a linker error of unresolved external symbol by linker at the place I was about to import and use that function (exact linker error:"unresolved external symbol "__declspec(dllimport) void _cdecl getString<5>(class String<5> &,unsigned char) (_imp_??$getString@$04@@YAXAAV?$String@$04@@E@Z)") because "num" was not specified at the point I was intending to instantiate; at the first place I was thinking that maybe because String<num> & string would be implemented as a pointer the following syntax would've been an instantiation but seems I was wrong.

template<size_t num> 
__declspec(dllexport) void getString(String<num> & string,unsigned char number);

Now how do you suggest I should do the instantiation because I'm not certainly going to do it for every single integer number found on earth!!!.

Was it helpful?

Solution 2

What it is, is a wrong design from the beginning, What I've done is not an explicit instantiation at all because even for different values of "size_t num" different instances of the function are generated opposite to what I was thinking at first so my kind of intended explicit instantiation is impossible with this design. for a right design the first parameter of the function should be an array to make the explicit instantiation possible for different types for "typename T". The right design would be as following:

template <typename T>
void getString(char string[],T number){
 cout <<string<<' '<<number<<'\n';
}
template __declspec(dllexport) void getString(char string[],unsigned char number);

OTHER TIPS

If it's a function template that you'd like to be able to instantiate for arbitrary parameters, then don't put it in your source files. Put it in the header file instead.

Obligatory links:

In your header declare:

template <size_t num,typename T>
void getString(String<num> & string,T number);

In you cpp file define:

template <>
void getString<42,int>(String<42,int> & string, int number){
  cout <<string.charArray<<' '<<number<<'\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top