首页 > 解决方案 > 无法在其 type-id 表达式中实例化包含 lambda 作为模板参数的别名模板

问题描述

考虑以下 C++20 代码:

template <class T>
struct TypeWrapper {};

template <auto F>
struct NonTypeWrapper {};

namespace using_value {
    using alias = NonTypeWrapper<42>;

    using user = TypeWrapper<alias>; //Ok
}

namespace using_value_with_template {
    template <bool B>
    using alias = NonTypeWrapper<42>;

    template <bool B>
    using user = TypeWrapper<alias<B>>; //Ok
}

namespace using_lambda {
    using alias = NonTypeWrapper<[] () {}>;

    using user = TypeWrapper<alias>; //Ok
}

namespace using_lambda_with_template {
    template <bool B>
    using alias = NonTypeWrapper<[] () {}>;

    template <bool B>
    using user = TypeWrapper<alias<B>>; //error: template argument 1 is invalid
}

(编译器-浏览器:https ://godbolt.org/z/bWGhn6PWW )

GCC 无法编译此代码并出现以下错误:

<source>:32:37: error: template argument 1 is invalid
   32 |     using user = TypeWrapper<alias<B>>; //error: template argument 1 is invalid
      |     

Clang 还不支持 lambdas 作为模板参数,所以我只能使用 GCC。

两个问题:

  1. 有什么理由不能实例化包含 lambdas 作为其类型 ID 表达式中的模板参数的别名模板,还是 GCC 错误?

  2. 为什么 GCC 会打印出如此无益的信息?编译器不应该至少给我们一个关于为什么参数无效的线索吗?

标签: c++gcc

解决方案


推荐阅读