【发布时间】:2020-07-23 19:52:27
【问题描述】:
我正在开发一个使用以下结构的代码库:
啊哈:
template<int N> void f();
void b();
a.cpp:
#include "a.h"
template<> void f<1>() {}
int main()
{
b();
}
b.cpp:
#include "a.h"
void b()
{
f<1>();
}
代码似乎可以正确构建和运行。
我的问题是:这是格式正确的,还是某种格式错误的 NDR 碰巧有效?
如果使用clang -Wundefined-func-template 构建(在我的 IDE 的 clang-tidy 默认设置中启用),则会产生警告:
b.cpp:5:2: warning: instantiation of function 'f<1>' required here, but no definition is available [-Wundefined-func-template]
f<1>();
^
./a.h:1:22: note: forward declaration of template entity is here
template<int N> void f();
^
b.cpp:5:2: note: add an explicit instantiation declaration to suppress this warning if 'f<1>' is explicitly instantiated in another translation unit
f<1>();
^
但我不确定是否只是禁用警告,或进行一些代码更改(除了将显式专业化定义移动到头文件,这对于这个项目来说不是更可取的)。
遵循警告消息中的建议并将显式实例化声明添加到头文件(即extern template void f<1>();)会导致错误消息(在显式实例化之前隐式实例化特化)。
但是,向头文件添加显式特化声明 template<> void f<1>(); 会抑制警告。但我不确定这是否是 (a) 必要的,和/或 (b) 推荐的样式。
【问题讨论】:
-
@LanguageLawyer 你能写一个答案吗?
-
如果我没看错的话,CWG 的解释是说对显式特化的调用至少需要在范围内声明特化,但对显式实例化的调用则不需要
-
@LanguageLawyer 好发现
标签: c++ templates language-lawyer one-definition-rule explicit-specialization