仅限 Xcode 9 - 如何解决由类模板中的静态变量引起的 [-Wundefined-var-template] 警告? [英] Xcode 9 only - How to resolve the [-Wundefined-var-template] warning caused by static variable in a class template?

查看:18
本文介绍了仅限 Xcode 9 - 如何解决由类模板中的静态变量引起的 [-Wundefined-var-template] 警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码在 Windows 和 Linux 上编译时没有警告或错误.它开始在 XCode 9 中收到 -Wundefined-var-template 警告.

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

推荐答案

我尝试过但没有奏效的方法:

  • 将 foo.cpp 中的代码移动到 foo.h 导致链接时出现重复代码"错误,因为 foo.h 包含在多个文件中.
  • 在头文件中添加以下代码可以解决警告,但代码在运行时失败.

  • 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 = "";

最终效果如何:

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";

这篇关于仅限 Xcode 9 - 如何解决由类模板中的静态变量引起的 [-Wundefined-var-template] 警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆