使用ConstexPR成员函数的ConstexPR成员变量的初始化
Initialization of constexpr member variable using constexpr member function
我想使用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>;
相关文章:
- 多成员Constexpr结构初始化
- constexpr构造函数需要常量成员函数时出现问题
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:初始化 constexpr 构造函数中的成员数组
- 初始化模板化类中的静态 constexpr 成员
- 静态 constexpr 成员变量初始化
- 静态数据成员:它"const declaration / constexpr definition"起作用?
- 使用静态 constexpr 成员的未解析外部符号
- 使用模板参数还包括 constexpr 成员函数enable_if单独定义和声明模板成员函数
- Constexpr成员函数
- 在模板定义中调用非静态constexpr成员函数
- 类成员参数中的Constexpr
- 在构造函数中使用 constexpr 成员
- 不带初始值设定项的 constexpr 静态数据成员
- emplace_back会导致静态 constexpr 成员上出现链接错误
- l值引用对象上的Constexpr成员函数:Clang和gcc不同意
- 在类外部初始化的 constexpr 静态成员的声明中是否需要 constexpr 说明符
- 现在允许重新定义 constexpr 静态数据成员吗?(但不是内联常量)?
- 是否可以以编程方式初始化 constexpr std::array 成员