C2491: 'std::numpunct<_Elem>::id' : def

2019-01-20 14:47发布

问题:

Given following code,

#include <sstream>
#include <stdint.h>

template <typename D> void func() {
    std::basic_stringstream<D> outStream;
    D suffix = 0;
    outStream << suffix;
}

void main() {
    func<char>();     // OK
    func<wchar_t>();  // OK
    func<uint16_t>(); // generates C2491
}

what does following compile error mean?

error C2491: 'std::numpunct<_Elem>::id' : definition of dllimport static data member not allowed

回答1:

You can't declare methods with

_declspec(dllimport)

and provide a definition for them.

The qualifier tells the compiler that the function is imported from a different library than the one you are compiling now, so it wouldn't make sense to provide a definition for it.

When including the header, the qualifier should be

_declspec(dllimport)

and when you are compiling the module that provides a definition for the method it should be:

_declspec(dllexport)

The usual way of doing this is:

#ifdef CURRENT_MODULE
#define DLLIMPORTEXPORT _declspec(dllexport)
#else
#define DLLIMPORTEXPORT _declspec(dllimport)
#endif

The define CURRENT_MODULE is only defined in the module that contains the definitions, so when compiling that module the method is exported. All other modules that include the header don't have CURRENT_MODULE defined and the function will be imported.

I'm guessing your directive - _declspecimport - is similar to this.