在`static_assert`,`if constexpr(...)`和`constexpr`变量之间的模板中对`constexpr` lambdas的评估不一致

Vit*_*meo 5 c++ lambda constant-expression constexpr c++17

(使用g++ 7.0trunk.)

鉴于以下"类型到价值包装"实用程序......

template <typename T>
struct type_wrapper { using type = T; };

// "Wraps" a type into a `constexpr` value.
template <typename T>
constexpr type_wrapper<T> type_c{};
Run Code Online (Sandbox Code Playgroud)

...我创建了以下函数来检查表达式的有效性:

template <typename TF>
constexpr auto is_valid(TF)
{
    return [](auto... ts) constexpr 
    {
        return std::is_callable<TF(typename decltype(ts)::type...)>{};
    };
}   
Run Code Online (Sandbox Code Playgroud)

is_valid功能可以使用如下:

// Evaluates to `true` if `some_A.hello()` is a valid expression.
constexpr auto can_add_int_and_float = 
    is_valid([](auto _0) constexpr -> decltype(_0.hello()){})
        (type_c<A>);

// Evaluates to `true` if `some_int + some_float` is a valid expression.
constexpr auto can_add_int_and_float = 
    is_valid([](auto _0, auto _1) constexpr -> decltype(_0 + _1){})
        (type_c<int>, type_c<float>);
Run Code Online (Sandbox Code Playgroud)

它也可以在里面使用static_assert......

static_assert(is_valid([](auto _0) constexpr -> decltype(_0.hello()){})
        (type_c<A>));
Run Code Online (Sandbox Code Playgroud)

......和里面if constexpr:

if constexpr(
     is_valid([](auto _0) constexpr -> decltype(_0.hello()){})
        (type_c<A>)) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

但是,当is_valid在模板函数内部使用(将模板参数作为type_c值传递)时,会发生一些奇怪的事情:

  • static_assert(is_valid(/*...*/)) 工作正常.

  • constexpr auto x = is_valid(/*...*/) 工作正常.

  • if constexpr(is_valid(/*...*/) 无法编译.

// Compiles and works as intended.
template <typename T0, typename T1>
void sum_ok_0(T0, T1)
{
    static_assert(
         is_valid([](auto _0, auto _1) constexpr 
              -> decltype(_0 + _1){})(type_c<T0>, type_c<T1>)
    ); 
}

// Compiles and works as intended.
template <typename T0, typename T1>
void sum_ok_1(T0, T1)
{
    constexpr auto can_sum =
         is_valid([](auto _0, auto _1) constexpr 
              -> decltype(_0 + _1){})(type_c<T0>, type_c<T1>); 

    if constexpr(can_sum) { }
}

// Compile-time error!
template <typename T0, typename T1>
void sum_fail_0(T0, T1)
{
    if constexpr(is_valid([](auto _0, auto _1) constexpr 
         -> decltype(_0 + _1){})(type_c<T0>, type_c<T1>)) { } 
}
Run Code Online (Sandbox Code Playgroud)

错误:

In function 'void sum_fail_0(T0, T1)':
64:95: error: expression '<lambda>' is not a constant expression
     if constexpr(is_valid([](auto _0, auto _1) constexpr -> decltype(_0 + _1){})(type_c<T0>, type_c<T1>)) { }
Run Code Online (Sandbox Code Playgroud)

为什么这不能仅针对if constexpr(is_valid(/*...*/))案例进行编译?这与static_assert和不一致constexpr auto x = /*...*/.

这是g++执行中的缺陷if constexpr吗?

关于wandbox的完整示例.

Vit*_*meo 1

不一致的行为被报告为bug #78131