问题
The sample code compiles without warning or error on Windows and Linux. It starts to get the -Wundefined-var-template warning in XCode 9.
foo.h:
template <typename T>
struct myClass
{
static const char* name;
};
foo.cpp:
#include "foo.h"
template<>
const char *myClass<int>::name = "int";
warning: instantiation of variable 'myClass<int>::name' required here, but no definition is available [-Wundefined-var-template]
note: forward declaration of template entity is here
static const char *name;
^
note: add an explicit instantiation declaration to suppress this warning if 'myClass<int>::name' is explicitly instantiated in another translation unit
回答1:
What I tried but didn't work:
- Moving the code in foo.cpp to foo.h resulted in "duplicate code" error at link-time, because foo.h was included by multiple files.
Adding the following code in the header file can resolve the warning, but the code fails at runtime.
template<T> const char *myClass<T>::name = "";
What worked in the end:
foo.h:
template <typename T>
struct myClass
{
static const char* name;
};
template <>
struct myClass<int>
{
static const char* name;
};
foo.cpp:
#include "foo.h"
const char *myClass<int>::name = "int";
来源:https://stackoverflow.com/questions/47230290/xcode-9-only-how-to-resolve-the-wundefined-var-template-warning-caused-by-s