且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当一个constexpr函数调用一个非constexpr时,在未实例化的模板中编译器错误

更新时间:2022-12-13 21:51:04



This line is fine:

S<int> s1;

但以下 get 的定义-formed:

but the following definition of get is ill-formed:

static constexpr S get() { return S(); }

,因为它不会返回文字类型,因为 S 没有constexpr构造函数。

since it does not return a literal type since S does not have a constexpr constructor.

从草案C ++ 11标准部分 7.1.5 constexpr说明符[dcl.constexpr]:

From the draft C++11 standard section 7.1.5 The constexpr specifier [dcl.constexpr]:


constexpr函数的定义应满足以下约束:

The definition of a constexpr function shall satisfy the following constraints:


  • 其返回类型应为文字类型;

及其后的部分(强调我的):


如果实例化的模板constexpr函数的专门化
类模板的成员函数或类模板的成员函数不能满足
constexpr函数或constexpr构造函数的要求
专业化不是constexpr函数或constexpr
构造函数。 [注意:如果函数是一个成员函数,它将
仍然是const,如下所述。 -end note] 如果模板的特殊化
没有产生一个constexpr函数或者constexpr
构造函数,程序就会失败;

注意,在非模板的情况下,gcc和clang都会产生一个错误,因为返回类型是不是文字查看实时

Note in the non-template case both gcc and clang generate an error since the return type is not a literal see it live.