且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试传递constexpr lambda并使用它来显式指定返回类型

更新时间:2023-02-12 23:35:42

constexpr函数的参数本身并不是constexpr对象-因此,不能在常量表达式中使用它们.您的两个返回array的示例都格式错误,因为没有有效的调用.

Parameters to constexpr functions are not themselves constexpr objects - so you cannot use them in constant expressions. Both of your examples returning arrays are ill-formed because there is no valid call to them.

要了解原因,请考虑以下废话示例:

To understand why, consider this nonsense example:

struct Z { int i; constexpr int operator()() const { return i; }; };

template <int V> struct X { };
template <typename F> constexpr auto foo(F f) -> X<f()> { return {}; }

constexpr auto a = foo(Z{2});
constexpr auto b = foo(Z{3});

Z具有constexpr调用运算符,其格式正确:

Z has a constexpr call operator, and this is well-formed:

constexpr auto c = Z{3}();
static_assert(c == 3);

但是如果允许更早使用,我们将有两个调用foo<Z>的调用,这些调用必须返回不同类型.仅当实际值f是模板参数时,这种情况才会出现.

But if the earlier usage were allowed, we'd have two calls to foo<Z> that would have to return different types. This could only fly if the actual value f were the template parameter.

请注意,clang编译声明本身并不是编译器错误.这是一类状况不佳的情况,不需要诊断.

Note that clang compiling the declaration is not, in of itself, a compiler error. This is a class of situations that are ill-formed, no diagnostic required.