修复警告 "Wundefined-var-template"

Fixing warning "Wundefined-var-template"

目前正在搜索重复项:

据我了解,其中 none 回答了 如何在类似于下面的 MCVE 的情况下使用 clang++ 3.8+ 摆脱 Wundefined-var-template 的问题?


文件a.h

#ifndef A_INCLUDED
#define A_INCLUDED

    template <class T>
    struct A
    {
        static const char *name;
    };

#endif

文件a.cpp

#include "a.h"

template <> const char* A<double>::name = "Johnny";
template <> const char* A<float>::name = "Dude";

文件b.cpp

#include <cstdio>
#include "a.h"

void say_it() {
    printf( "%s\n", A<double>::name );
}

运行 来自终端:

$ clang++ -c -o a.o -std=c++11 a.cpp
$ clang++ -c -o b.o -std=c++11 b.cpp a.o
clang: warning: a.o: 'linker' input unused [-Wunused-command-line-argument]
b.cpp:5:32: warning: instantiation of variable 'A<double>::name' required here, but no definition is available [-Wundefined-var-template]
    printf( "%s\n", A<double>::name );
                               ^
./a.h:7:28: note: forward declaration of template entity is here
        static const char *name;
                           ^
b.cpp:5:32: note: add an explicit instantiation declaration to suppress this warning if 'A<double>::name' is explicitly instantiated in another translation unit
    printf( "%s\n", A<double>::name );
                               ^
1 warning generated.

Demo

按照警告信息说明,添加(在a.h中):

template <> const char* A<double>::name;

Demo