带有模板的类型类型

Types of types with templates?

本文关键字:类型      更新时间:2023-10-16
template<???>    
struct Container{
  T t;
  M<T> v;
}

其中Container<vector<int>>应该生成

struct Container{
 int t;
 vector<int> v;
}

我可以用模板来表达吗?

是:

template<typename T, template <typename, typename> class M>
struct Container {
    T t;
    M<T,std::allocator<T>> v;
};

使用:

Container<int,std::vector>
交替

:

template <typename C>
struct Container {
    typename C::value_type t;
    C v;
};

并与:

连用
Container<std::vector<int>>

保持模板简单,否则你会头疼的。

template<class CONTAINER>
struct Container
{
    typedef CONTAINER container_type;
    typedef typename container_type::value_type value_type;
    value_type t;
    container_type v;
};

是的,有几种方法。您可以要求类型参数为定义了value_type的容器:

template <typename T>    
struct Container {
  typename T::value_type t;
  T v;
};

(如果T不是具有value_type类型定义的某个类,它将无法编译),或者您可以做一些更复杂的事情。如果可能的话,我会要求定义value_type