8

Consider a small toned down use case of my problem wherein I have a header as follows

#include <iostream>
#pragma once
#ifndef HEADER_H
#define HEADER_H
template<typename T>
class FOO
{
public:
    void func() { std::cout << "Foo!"; };
};

extern template class __declspec(dllexport) FOO<int>;
using myfoo = FOO<int>;
#endif

and a source file as

#include "Header.h"

int main()
{
    myfoo f;
    f.func();
    return 0;
}

When I compile this with VS 2015 (Update 3), I get following warning

warning C4910: 'FOO<int>': '__declspec(dllexport)' and 'extern' are incompatible on an explicit instantiation

MSDN page does not explain to me clearly why is it wrong to have extern and dllexport in explicit template declaration.

Can anybody please explain what is the rationale behind this ?

cpplearner
  • 13,776
  • 2
  • 47
  • 72
Recker
  • 1,915
  • 25
  • 55
  • 7
    `__declspec(dllexport)` says: "this is the definition of an object or function, which should be exported from a DLL". `extern` says: "this is merely a declaration; the definition is somewhere else". The two make no sense together. You likely want `template class __declspec(dllexport) FOO;`, and you want it in a source file, not in a header. – Igor Tandetnik Apr 04 '17 at 13:37
  • If you wish a dll, use extern "C" for classes and funcs, and make a macro for switching between __declspec(dllimport) for your .cpp-file and __declspec(dllexport) for dll header. – I.S.M. Apr 04 '17 at 13:39
  • I want to export an explicit template instantiation but I also want to avoid the code bloat which I read [here](http://www.stroustrup.com/C++11FAQ.html#extern-templates). May be I am mixing up two things ? Am I ? – Recker Apr 04 '17 at 13:40
  • 1
    You can declare it with `extern` in a header file, and define with `__declspec(dllexport)` in a source file. You can't do both on the same line though. – Igor Tandetnik Apr 04 '17 at 13:50

0 Answers0