Trying to pass a constexpr lambda and use it to explicitly specify returning type

后端 未结 1 1359
时光说笑
时光说笑 2021-01-21 01:03

I would like to use a function and pass a constexpr lambda. However, it only compiles successfully if I let the type be deduced through auto. Explicitl

相关标签:
1条回答
  • 2021-01-21 01:57

    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 has a constexpr call operator, and this is well-formed:

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

    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.


    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.

    0 讨论(0)
提交回复
热议问题