为什么模板允许constexpr函数成员与非constexpr构造函数一起使用? [英] Why do templates allow constexpr function members with non-constexpr constructors?

查看:87
本文介绍了为什么模板允许constexpr函数成员与非constexpr构造函数一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 14。为什么会这样编译:

Using C++14. Why will this compile:

template<unsigned N>
constexpr bool foo()
{
    std::array<char, N> arr;
    return true;
}

但不是这个吗?

constexpr bool foo()
{
    std::array<char, 10> arr; // Non-constexpr constructor 'array' cannot be used in a constant expression
    return true;
}


推荐答案

§7.1.5[dcl .constexpr] / p6:

§7.1.5 [dcl.constexpr]/p6:


如果 constexpr 函数的实例化模板特化
模板或类模板的成员函数将无法满足
constexpr 函数或 constexpr
构造函数,该专业化仍然是 constexpr 函数或
constexpr 构造函数,即使对该函数的调用不能
出现在常量表达式中。如果没有专门的模板
可以满足 constexpr 函数或
constexpr 的要求构造函数被视为非模板函数或
构造函数时,模板格式错误;不需要诊断。

If the instantiated template specialization of a constexpr function template or member function of a class template would fail to satisfy the requirements for a constexpr function or constexpr constructor, that specialization is still a constexpr function or constexpr constructor, even though a call to such a function cannot appear in a constant expression. If no specialization of the template would satisfy the requirements for a constexpr function or constexpr constructor when considered as a non-template function or constructor, the template is ill-formed; no diagnostic required.

对于 constexpr 函数模板有效不满足 constexpr 要求的特殊化,并且只要不在需要常量表达式的上下文中使用这些特殊化,就是有效的。

It is valid for constexpr function templates to have some specializations that do not satisfy the constexpr requirements, and it is valid to use those specializations as long as they are not in a context that requires a constant expression.

这是无效的,但是,如果模板的特殊化不能满足 constexpr 的要求。由于在一般情况下无法确定函数模板的所有可能实例化是否都不能满足 constexpr 的要求,因此该标准不需要诊断。因此,您的代码格式错误,不需要进行诊断-编译器可以但不要求报告错误。

It isn't valid, however, if no specialization of the template could satisfy constexpr requirements. Since in the general case it is impossible to determine whether all possible instantiations of a function template will fail to satisfy the constexpr requirements,the standard doesn't require a diagnostic. Hence, your code is ill-formed with no diagnostic required - the compiler can, but is not required to, report an error.

这篇关于为什么模板允许constexpr函数成员与非constexpr构造函数一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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