Warm tip: This article is reproduced from serverfault.com, please click

c++-即使无处调用模板函数,static_assert编译也会失败

(c++ - static_assert fails compilation even though template function is called nowhere)

发布于 2013-01-31 23:55:00

我使用带有标志c ++ 0x的g ++ 4.6.3(当前是ubuntu 12.04的默认软件包),但我偶然发现了这一点:

template <typename T>
inline T getValue(AnObject&)
{
    static_assert(false , "this function has to be implemented for desired type");
}

编译错误:

static_assertion failed "this function has to be implemented for the desired type"

即使我还没有在任何地方调用这个函数

它是g ++错误吗?仅当在代码中的某处调用此函数时,才应实例化该函数。

Questioner
Stephane Rolland
Viewed
0
Andy Prowl 2013-02-01 08:07:16

这是因为条件不以任何方式取决于模板参数。因此,编译器甚至可以在实例化该模板之前对其进行评估,如果评估结果合格,则生成关联的编译错误消息false

换句话说,这不是错误。尽管只有在实例化模板后才能检查很多事情,但是编译器甚至可以执行其他有效性检查。例如,这就是C ++具有两阶段名称查找的原因。编译器只是在想帮助你找到可能100%发生的错误。