【问题标题】:partial type as template argument c++ [duplicate]部分类型作为模板参数c ++ [重复]
【发布时间】:2014-04-18 16:52:03
【问题描述】:

简单地说,我可以将std::vector 作为模板参数传递吗?以下示例列表用法

tempate<typename container_t, typename value_t>
struct container_types
{
  typedef container_t<value_t> value_container_t;
  typedef container_t<pair<value_t> pair_container_t;

};

我希望通过 container_types 来生成最后两种数据类型。 如果这不可行,那么我该如何实现。

【问题讨论】:

  • 可以做到这一点,但它通常没有你想象的那么有用。通常最好传入您要用于数据成员的实际类型。
  • @juanchopanza:同意它是重复的。
  • @Kerrek SB:可能。但我沿着这条路走下去,看看它会带来多少麻烦。这在某些情况下会很有用。

标签: c++ templates template-meta-programming


【解决方案1】:

是的,像这样

#include <iostream>
#include <vector>

template <template<typename T> class container_t, typename value_t>
struct container_types
{
    typedef container_t<value_t> value_container_t;
    typedef container_t<std::pair<value_t,value_t > > pair_container_t;
};

template <typename T>
using my_vector = std::vector<T>;

int main(int argc,char** argv)
{
    container_types<my_vector,int>::value_container_t buff(100);
    std::cout << buff[50] << std::endl;
}

请注意,我必须用 my_vector 包装 std::vector,因为 std::vector 实际上有几个模板参数。

【讨论】:

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