static_assert即使模板函数无法调用也无法编译 [英] static_assert fails compilation even though template function is called nowhere

查看:1542
本文介绍了static_assert即使模板函数无法调用也无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用g ++ 4.6.3,(目前默认包为ubuntu 12.04)与标志c ++ 0x,我绊倒这:

  template< typename T> 
inline T getValue(AnObject&)
{
static_assert(false,此函数必须实现所需类型);
}

编译错误:


$ b b

  static_assertion failed此函数必须实现所需类型


b $ b

即使我不在任何地方调用此函数



这是一个g ++错误吗?不应该仅仅在代码中的某处调用该函数。

解决方案

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

换句话说,这不是一个错误。虽然许多事情只能在模板被实例化时被检查,但是还有其他的有效性检查,编译器甚至可以在之前执行。这就是为什么C ++有一个两阶段名称查找,例如。编译器只是试图帮助您找到100%可能发生的错误。


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");
}

with the compilation error:

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

even though I don't call this function anywhere yet.

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

解决方案

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.

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即使模板函数无法调用也无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆