实例化模板时出现短路? [英] Short-circuiting while instantiating template?

查看:167
本文介绍了实例化模板时出现短路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此代码段,

template<bool b>
struct other
{
    static const bool value = !b;
};

template<bool b>
struct test
{
    static const bool value = b || other<b>::value;
};

int main()
{
      bool value = test<true>::value;   
}

Do compilers instantiate other< true> 在上面的情况下,当实例化似乎完全不必要?或者只是因为我写了语法 other< b> :: value ,编译器必须实例化它,而不管它对于 test< true> :: value

Do compilers instantiate other<true> in situations such as the above, when instantiating seems completely unnecessary? Or just because I've written the syntax other<b>::value, compilers must instantiate it regardless of the fact that it contributes absolutely nothing to the calculation of the value of test<true>::value?

我想听听,a) ,以及b)由各种编译器实现的实际是什么?

I would like to hear, a) what is required by the Standard, and b) what is actually implemented by the various compilers? Relevant sections from the Standard would be appreciated.

推荐答案

根据C ++规范,$ 14.7.1 / 4节:

According to the C++ spec, section $14.7.1/4:


类模板特化是
隐式实例化如果类
类型在上下文中使用
需要一个完全定义的对象
类型或者如果
类类型的完整性影响
程序的语义
;特别是如果
表达式其类型是类
模板专用化涉及
重载解析

"A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the completeness of the class type affects the semantics of the program; in particular, if an expression whose type is a class template specialization is involved in overload resolution"

短路,类将必须有一个完整的类型,因为你正在寻找它的内部找到值的静态成员。这会阻止编译器将表达式短路。

In the case you illustrated with short-circuiting, the class would have to have a complete type, because you're looking inside of it to find the value static member. This precludes the compiler from short-circuiting the expression.

至于在实践中实际发生的事情,我不知道,因为我看不到编译器会如何得到离开,不做实例化。例如,假设其他< b> 的实例化如下:

As for what actually happens in practice, I'm not sure because I can't see how the compiler could get away with not doing the instantiation. For example, suppose that the instantiation of other<b> looked like this:

template <bool B> struct other {
    typedef int value;
};

在这里,您的程序将是错误的,因为其他< b& / code> :: value是一个类型,而不是值,但编译器无法诊断错误,而实际上没有实例化。

Here, your program would be ill-formed because other<b>::value is a type, not a value, but the compiler couldn't diagnose the error without actually doing the instantiation.

这篇关于实例化模板时出现短路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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