Constexpr方法用于非Constexpr类



如果类没有constexpr构造函数,是否有任何理由将constexpr添加到类的方法中?也许编译器可以做一些优化在这种情况下?

是的,一个明显的例子是当类是聚合类时。聚合初始化不调用任何构造函数,但仍可用于常量表达式求值。

即使类不是聚合类,如果成员函数不访问类实例的任何状态,您仍然可以在常量表达式求值中调用constexpr成员函数。这显然适用于static成员函数,但也适用于非static成员函数。

例如:

struct A {
int i;        
// The only usable constructor is the default constructor,
// which is not `constexpr`.
// The class is also not an aggregate class because of these declarations.
A() : i(0) {}
A(const A&) = delete;
constexpr int getZero() {
// return i; would be IFNDR
return 0;
}
};
int main() {
A a;
constexpr int x = a.getZero();
}
但是您必须小心,因为如果完全不可能将成员函数作为任何常量表达式的子表达式调用,那么无论如何将其标记为constexpr都会使程序格式不良,不需要诊断(IFNDR)。换句话说,编译器可能会拒绝编译这样的程序。

同样,这种情况出现的频率以及期望使用恒定求值用例的频率(特别是对于非static成员函数)是另一个问题。

最新更新