Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

warning C4661:no suitable definition provided for explicit template instantiation request

I wrote a class template and use it in different DLLs, so wish to hide some parts of the implementation.

To do this, I use "template instantiation", but export it, like this, here is the header file:

#include <iostream>
#include <exception>

using namespace std;

template<typename T>
class __declspec(dllexport) Templated
{
    public:
        Templated();
};

template __declspec(dllexport) Templated<int>;

int main()
{
   cout << "Hello World" << endl; 
}

And the definition is in a separate file (.cpp)

template<typename T>
Templated<T>::Templated() {}

template Templated<int>;

My problem is that I got a warning, even if the instantiation is marked as exported!

You can test this code here : http://webcompiler.cloudapp.net/, it will generate the C4661 warning!

Is this normal?

like image 708
CDZ Avatar asked May 24 '17 13:05

CDZ


1 Answers

You declare an explicit instantiation of your template. That's fine, but you fail to provide a definition for the constructor: you only declare it, and there is no definition for the template nor it's instantiation.

You must provide a definition either in the template itself:

...
public:
    Templated() {};  // empty but defined ctor
...

or for the specialization:

Templated<int>::Templated() {
}

From your comment and edit to question, the definition is in another cpp file. The problem is that for the compiler, each cpp file is a different translation unit. Said differently, when the first file is compiled, the compiler does not know the other one. That's the reason why you get a warning and not an error: the warning means hey programmer, you declare me that you want a specialized instantiation of Templated, but I cannot find its constructor. Hope you have defined it in another translation unit, because if you have not you'll get an error at link time. As you have actually defined it in another file, you can safely ignore the warning.

A warning only says that something uncommon is occuring. Normally, it is expected for the declaration of an explicit specialization to be in the same translation unit as all its required definitions. And IMHO, you should stick to that usage to avoid the warning and, more importantly, to have a more maintainable application.

like image 187
Serge Ballesta Avatar answered Nov 13 '22 19:11

Serge Ballesta