【问题标题】:Fixing warning "Wundefined-var-template"修复警告“Wundefined-var-template”
【发布时间】: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.

Demo

【问题讨论】:

标签: c++11 compiler-warnings clang++


【解决方案1】:

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

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

Demo

【讨论】:

  • 当我允许时会接受;我不清楚“显式实例化声明”是什么意思,或者应该在哪里插入。另请参阅this post
  • 你确定这是声明而不是定义?
  • @Quentin 这正是this post 的意义所在。我正在犹豫是否将我的问题作为重复来结束..
  • 这是一个声明。 C++17 在 [17.7.3.13] 中说:“如果声明包含初始化器,则模板的静态数据成员的显式特化或静态数据成员模板的显式特化是定义;否则,它是声明。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 2017-05-31
  • 1970-01-01
  • 2019-12-07
  • 2019-08-08
  • 2020-11-28
  • 2017-10-25
相关资源
最近更新 更多