【问题标题】:How to specialize a variadic template struct for particular number of template arguments如何为特定数量的模板参数专门化可变参数模板结构
【发布时间】:2018-03-05 21:56:35
【问题描述】:

采用以下模板结构:

template<int n, typename... Ts>
struct Widget {};

如何针对sizeof...(Ts) == n 的情况进行专门化?例如。 Widget&lt;3, int, char&gt; 应该解析为主模板,但Widget&lt;3, int, char, double&gt; 应该解析为专业化。

我尝试过使用通常的 SFINAE 模式,但问题是模板参数包必须是最后一个模板参数,因此无法在 typename... Ts 之后插入 SFINAE 检查。

【问题讨论】:

    标签: c++ c++11 templates metaprogramming variadic-templates


    【解决方案1】:

    您可以使用辅助类:

    // for your primary template
    template<int n, bool b, class... Ts>
    struct Widget_impl {};
    
    // for your specialization
    template<class... Ts>
    struct Widget_impl<sizeof...(Ts), true, Ts...> {};
    
    template<int n, typename... Ts>
    using Widget = Widget_impl<n, n == sizeof...(Ts), Ts...>;
    

    其实你的case可以直接做:

    // for your primary template
    template<int n, class... Ts>
    struct Widget {};
    
    // for your specialization
    template<class... Ts>
    struct Widget<sizeof...(Ts), Ts...> {};
    

    因为sizeof...(Ts) == n 已经是专业化的情况。

    【讨论】:

      【解决方案2】:

      您不能在typename... Ts 之后插入 SFINAE 检查,但可以在之前插入:

      template<typename AlwaysVoid, int n, typename... Ts>
      struct WidgetImpl {};
      
      // ...
      
      template <int n, typename... Ts>
      struct WidgetImpl<std::enable_if_t<sizeof...(Ts) == n>, n, Ts...> {
          // ...
      };
      

      然后,你可以给它起别名:

      template <int n, typename... Ts>
      using Widget = WidgetImpl<void, n, Ts...>;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多