Xcode 9 only - 如何解决 class 模板中静态变量引起的 [-Wundefined-var-template] 警告?
Xcode 9 only - How to resolve the [-Wundefined-var-template] warning caused by static variable in a class template?
示例代码在 Windows 和 Linux 上编译时没有警告或错误。它开始在 XCode 9.
中收到 -Wundefined-var-template
警告
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
我试过但没有用的:
- 将 foo.cpp 中的代码移动到 foo.h 会导致 link 时出现 "duplicate code" 错误,因为 foo.h 被多个文件包含。
在头文件中添加如下代码可以解决警告,但是代码运行时失败
template<T>
const char *myClass<T>::name = "";
最后的效果:
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";
示例代码在 Windows 和 Linux 上编译时没有警告或错误。它开始在 XCode 9.
中收到-Wundefined-var-template
警告
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
我试过但没有用的:
- 将 foo.cpp 中的代码移动到 foo.h 会导致 link 时出现 "duplicate code" 错误,因为 foo.h 被多个文件包含。
在头文件中添加如下代码可以解决警告,但是代码运行时失败
template<T> const char *myClass<T>::name = "";
最后的效果:
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";