使用ConstexPR成员函数的ConstexPR成员变量的初始化

Initialization of constexpr member variable using constexpr member function

本文关键字:成员 ConstexPR 初始化 变量 函数 使用      更新时间:2023-10-16

我想使用constexpr成员函数初始化constexpr成员变量,但没有编译。当我将功能移出班级时,没关系。为什么会发生?有什么方法可以使用类成员constexpr函数来初始化成员constexpr变量?

我正在使用Apple LLVM版本8.0.0(Clang-800.0.38)。

感谢您的任何帮助。

constexpr static int Add_Ext(int a, int b) { return a + b; }

class Foo
{
public:
    constexpr static int Add_InClass(int a, int b) { return a + b; }
    // This is OK.
    constexpr static int kConstantX = Add_Ext(1, 2);
    // This results in a compile error.
    constexpr static int kConstantY = Add_InClass(1, 2);
};

clang错误消息:

Constexpr variable 'kConstantY' must be initialized by a constant expression

来自CWG-1255和CWG-1626

标准应清楚地表明,constexpr成员函数在恒定表达式完成之前不能使用。

似乎您的代码是故意不可接受的。但是,标准应该使它在此方面更加清楚。

有什么方法可以使用类Member ConstexPR函数来初始化成员ConstexPR变量?

W.R.T。那些dr,不。

感谢Danh。我研究了您告诉的WG线程,毕竟,如果将其制作为类模板,我发现我可以使用成员Constexpr函数。

// This works (it doesn't if you make it as a non-template class).
template <typename T>
class TemplateFoo
{
public:
    constexpr static T Add_InClass(T a, T b) { return a + b; }
    constexpr static T kConstantY = Add_InClass(1, 2);
};
// Even such a meaningless template works too. 
template <typename T>
class TemplateBar
{
public:
    constexpr static int Add_InClass(int a, int b) { return a + b; }
    constexpr static int kConstantY = Add_InClass(1, 2);
};
// So, this would be a (dirty but) useful workaround 
// when you don't want to use the class as a template.
// Any type could be used as the template argument, which has no meaning.
using Bar = TemplateBar<char>;