我使用带有标志 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 编译失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)