【发布时间】:2019-10-21 02:42:08
【问题描述】:
目前搜索重复项:
- This post 专门处理单例实现的情况,其中答案通过不同的实现完全避免了警告。
- This post 在没有解决问题的情况下自行回答。
- suggested duplicate 解释了如何实现模板成员函数(不相关)。
- 另一个suggested duplicate 解释如何定义模板静态成员(不相关)。
据我了解,这些都没有回答 在类似于下面的 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.
【问题讨论】:
-
IIRC 这只是
extern template <> const char* A<double>::name;等等,如警告所示。
标签: c++11 compiler-warnings clang++