【问题标题】:How take param of the template template class如何获取模板模板类的参数
【发布时间】:2011-11-23 19:59:15
【问题描述】:

我有一个像Type<Param> 这样的类型。如何在 c++11 中检索参数?

可能是这样的:

// I know it's not correct but it conveys the idea very well
template
<
   template <class Param> class Type 
>
struct GetParam
{
   typedef Param Result;
};

// e.g.
typedef GetParam<std::vector<double>>::Result X; // must return double
typedef GetParam<std::list<double>>::Result X; // double
typedef GetParam<std::vector<std::list<double>>::Result X; // std::list<double>

【问题讨论】:

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


【解决方案1】:
template<class Type>
struct GetParam;

template<template<typename ...> class Tmp, typename T1, typename ...Types>
struct GetParam<Tmp<T1, Types...>> {
  typedef T1 type;
};

但是,您传递给GetParam 的类模板特化只能有类型模板参数。因此,例如,您不能通过 std::array。做一个完全通用的GetParam 是不可能的,因为您必须征用所有可能的模板参数列表种类,而且基本上是无限多的。

【讨论】:

    【解决方案2】:

    看起来 tr2 可能在类型特征中有一个类型列表。 使用 g++-4.7 你可以这样写:

    template<class Type>
      struct GetParam2;
    
    template<template<typename ...> class Tmpl, typename Type, typename ...Types>
      struct GetParam2<Tmpl<Type, Types...>>
      {
        typedef typename std::tr2::typelist<Type, Types...> tlist;
        typedef typename tlist::first::type type;
        typedef typename tlist::rest::type types;
      };
    
    typedef GetParam2<std::vector<double>>::type dbl2; // double
    static_assert(std::is_same<dbl, dbl2>::value, "Ouch");
    typedef GetParam2<std::list<double>>::type dbl2; // double
    typedef GetParam2<std::vector<std::list<double>>>::type listdbl2; // std::list<double>
    static_assert(std::is_same<listdbl, listdbl2>::value, "Ouch");
    typedef GetParam2<std::array<double, 3>>::type arrdbl; // std::list<double>
    

    除了数组的最后一行之外,一切正常。可能是我用错了。

    这与 johannes-schaub-litb 的答案大致相同,但如果有库支持会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      相关资源
      最近更新 更多