即使在任何地方都没有调用模板函数,static_ass

static_assert fails compilation even though template function is called nowhere(即使在任何地方都没有调用模板函数,static_assert 编译失败)

本文介绍了即使在任何地方都没有调用模板函数,static_assert 编译失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use g++ 4.6.3, (currently default package for ubuntu 12.04) with the flag c++0x, and I stumble across this:

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++ 错误吗?仅当在代码中的某处调用此函数时,才应实例化该函数.

Is it a g++ bug ? Shouldn't this function be instanciated only if it is called somewhere in the code.

推荐答案

那是因为条件不以任何方式依赖于模板参数.因此,编译器甚至可以在实例化该模板之前对其进行评估,如果评估结果为 false,则会生成相关的编译错误消息.

That's because the condition does not depend in any way on the template parameters. Therefore, the compiler can evaluate it even before instantiating that template, and produces the associated compilation error message if it the evaluation yields false.

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

In other words, this is not a bug. Although many things can only be checked once a template is instantiated, there are other validity checks that a compiler can perform even before. This is why C++ has a two-phase name lookup, for instance. The compiler is just trying to help you finding errors that are 100% likely to occur.

这篇关于即使在任何地方都没有调用模板函数,static_assert 编译失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:即使在任何地方都没有调用模板函数,static_ass

基础教程推荐