即使模板函数在任何地方都没有调用,static_assert 也无法编译 [英] static_assert fails compilation even though template function is called nowhere

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

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