#include <utility>
struct A {
constexpr auto one(int a) {
return std::integral_constant<int, _data[a]>{};
}
constexpr int two(int a) const {
return _data[a];
}
int _data[10];
};
int main() {
constexpr auto ex = A{{1,2,3,4,5,6,7,8,9,10}};
std::integral_constant<int, ex.two(3)> b{};
}
上面的代码不会在主干铛中编译。该错误是在one()
成员函数,并说:C++ constexpr自动成员函数。铿锵的问题?
cc.cpp:57:44: note: implicit use of 'this' pointer is only allowed
within the evaluation of a call to a 'constexpr' member function.
显然,函数标记为constexpr
,如果你注释掉one()
成员,一切编译罚款,所以我们显然能够从创建integral_constant
ex
,但不是直接从struct
?这似乎是,当我需要auto
返回类型扣除,它失败并声称该功能不是constexpr
?
这是预期吗?我觉得这不应该是一个问题,如果这是预期的行为,我会感到惊讶。
'_data [a]'不是'A :: one'内的常量表达式。请注意,'constexpr'函数仍然可以在运行时调用,例如如果您提供仅在运行时已知的参数。 – dyp
这是'two'中的一个constexpr,通过使用它的返回值作为模板参数来证明它? – pat
据我所知,'_data [a]'在两个成员函数中都不是一个常量表达式。但是constexpr函数可以由非常量表达式组成。规则是:在需要一个常量表达式的上下文中,不可以评估非常量的东西(包括一个constexpr函数的一部分)。另外,在需要常量表达式的上下文中,必须有一种方法可以合法调用'constexpr'函数。 – dyp