Xcode 9 only - How to resolve the [-Wundefined-var-template] warning caused by static variable in a class template?

删除回忆录丶 提交于 2020-01-07 04:53:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!