【发布时间】:2015-05-06 23:02:42
【问题描述】:
#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{};
}
上面的代码不会在trunk Clang中编译。错误在one() 成员函数中,并说:
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()成员,一切编译正常,所以我们显然能够从ex创建integral_constant,但不能直接从struct?看来,当我需要auto 返回类型推导时,它失败并声称该函数不是constexpr?
这是预期的吗?我觉得这应该不是问题,如果这是预期的行为,我会感到惊讶。
【问题讨论】:
-
_data[a]不是A::one中的常量表达式。请注意,constexpr函数仍然可以在运行时调用,例如如果您提供仅在运行时才知道的参数。 -
它是
two内部的一个constexpr,通过使用它的返回值作为模板参数来证明? -
据我所知,
_data[a]在两个成员函数中都不是常量表达式。但是 constexpr 函数可以由非常量表达式组成。规则是:在需要常量表达式的上下文中,不得评估非常量的事物(包括 constexpr 函数的一部分)。此外,必须有一种方法可以在需要常量表达式的上下文中合法调用constexpr函数。 -
@polkovnikov.ph
two不知道该实例已被声明为constexpr。考虑A a {rand()}; a.two(0)。这是完全合法的,但函数调用表达式a.two(0)不能是常量表达式。 -
@polkovnikov.ph 请注意,我只使用了
a.two(0),但您在需要常量表达式的上下文中使用它。正如我所说:在这个例子中,a.two(0)是合法的,但它本身不是常量表达式,也不能在常量表达式中求值。
标签: c++ c++11 auto c++14 constexpr