【问题标题】:Xcode 9 only - How to resolve the [-Wundefined-var-template] warning caused by static variable in a class template?仅限 Xcode 9 - 如何解决由类模板中的静态变量引起的 [-Wundefined-var-template] 警告?
【发布时间】:2017-11-10 20:02:45
【问题描述】:

示例代码在 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

【问题讨论】:

标签: c++ xcode xcode9


【解决方案1】:

我试过但没用:

  • 将 foo.cpp 中的代码移动到 foo.h 会导致链接时出现“重复代码”错误,因为 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";

【讨论】:

  • 这如何解决问题?您只是定义了整个模板的特化,这违背了模板的重点
猜你喜欢
  • 2019-10-21
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2016-03-05
  • 2017-04-11
  • 1970-01-01
相关资源
最近更新 更多