【问题标题】:Workaround for passing parameter pack to alias templates (which have non-pack parameters)将参数包传递给别名模板(具有非包参数)的解决方法
【发布时间】:2022-01-18 01:34:45
【问题描述】:

看这个例子:

template <typename A>
struct Foo1 {};

template <typename A, typename B>
struct Foo2 {};

struct Bar1 {
    template <typename A>
    using Foo = Foo1<A>;
};

struct Bar2 {
    template <typename A, typename B>
    using Foo = Foo2<A, B>;
};

template <typename BAR>
struct Something {
    template <typename ...P>
    void func(typename BAR::template Foo<P...> foo) {
    } 
};

我想实现:如果Something专门化了Bar1,那么我想有一个模板函数func,即:

   template <typename A>
   void func(Foo1<A> foo)

如果Something 专门用于Bar2,那么func 应该是:

   template <typename A, typename B>
   void func(Foo2<A, B> foo)

但是,这种直截了当的方法是行不通的,因为clang报错(需要实例化Something&lt;BarX&gt;让clang报这个错误):

错误:包扩展用作别名模板的非包参数的参数 void func(typename BAR::template Foo

foo) {

因此,别名模板似乎不是 100% 透明的(我发现了一些关于此的讨论:CWG 1430,这是设计使然)。

有解决这个问题的方法吗?

(gcc 编译此代码,但根据 CWG 1430,这可能是无意的)

【问题讨论】:

    标签: c++


    【解决方案1】:

    解决方法是使别名可变:

    struct Bar1 {
        template <typename... Ts>
        using Foo = Foo1<Ts...>;
    };
    
    struct Bar2 {
        template <typename... Ts>
        using Foo = Foo2<Ts...>;
    };
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      • 2019-08-30
      • 2022-08-18
      • 2011-05-28
      • 2015-09-07
      • 2023-01-25
      相关资源
      最近更新 更多