【问题标题】:Choose member type based on template arguments?根据模板参数选择成员类型?
【发布时间】:2017-09-11 02:50:12
【问题描述】:

如果我有一个模板类:

template<int N>
class C{
    Something _x;
}

我想根据N 的值来控制类成员_x 的类型。假设 N 为 0 则 _x 应为 A 型,否则 _x 应为 B 型。

这可能吗?

我不想只将类型作为模板参数传递,因为这可能会违反确定使用哪种类型的规则。例如我可以做C&lt;1, A&gt; 这是不正确的。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    对于只有几种可能类型的场景,您可以使用std::conditional

    #include <type_traits>
    
    struct A {};
    struct B {};
    
    template<int N>
    class M {
    public:
        std::conditional_t<N == 0, A, B> _x;
    };
    

    【讨论】:

      【解决方案2】:

      这可能吗?

      是的。也不是太难。

      template<int N>
      class C{
          typename c_member<N>::type _x;
      }
      

      在哪里

      struct A {};
      struct B {};
      
      template <int N> struct c_member
      {
         using type = B;
      };
      
      template <> struct c_member<0>
      {
         using type = A;
      };
      

      如果您愿意,您可以添加更多 c_member 的特化。

      【讨论】:

      • 我会选择另一个答案(因为它更简单)但是谢谢!
      • @user997112,没问题。
      【解决方案3】:

      有很多方法可以做到这一点。我喜欢重载,asmit 允许轻松扩展。

      template<int N>using int_t=std::integral_constant<int,N>;
      template<class T>struct tag_t{using type=T; constexpr tag_t(){}};
      template<class Tag>using type=typename Tag::type;
      
      struct A{}; struct B{};
      inline tag_t<A> something(int_t<0>){return {};}
      template<int x>
      inline tag_t<B> something(int_t<x>){return {};}
      

      现在我们只是:

      template<int N>
      class M {
      public:
        type<decltype(something(int_t<N>{}))> _x;
      };
      

      唯一的好处是您可以使用重载解析的全部力量来选择类型,并且您不必搞乱模板专业化,并且您不必制作一个复杂的条件来涵盖许多情况。

      如果您要在两种逻辑简单的类型之间进行选择,那就大材小用了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 2014-07-26
        • 2016-05-31
        • 1970-01-01
        • 1970-01-01
        • 2015-03-31
        • 1970-01-01
        相关资源
        最近更新 更多