c++ - 将标准容器传递给模板化类

标签 c++ templates

为什么这行不通?

template <typename T, typename U>  
class TSContainer {  
private:  
   U<T> container;  
};

称为:

TSContainer<int, std::vector> ts;

我认为解决方案可能是:

template <typename T, template <typename> typename C>  
class TSContainer  
{  
        C<T> container;  
};

但这也不起作用。

最佳答案

这是你需要的:

#include <vector>
template <typename T, template<typename, typename> class C>  
class TSContainer  
{  
    C<T, std::allocator<T> > container;  
};

int main() {
  TSContainer<int, std::vector> a;
}

请注意,std::vector 采用两个模板参数,第二个默认为 std::allocator。或者,您可以这样写:

#include <vector>
template <typename T, template<typename, typename = std::allocator<T> > class C>  
class TSContainer  
{  
        C<T> container;  
};

int main() {
  TSContainer<int, std::vector> a;
}

这两者都会强制您选择分配器。如果你想控制你的 vector 使用哪个分配器(即什么被用作 C 的第二个模板参数),你也可以使用这个:

#include <vector>
template <typename T, template<typename, typename> class C, typename A = std::allocator<T> >  
class TSContainer  
{  
        C<T, A> container;  
};

int main() {
  TSContainer<int, std::vector> a;
}

这是最灵活的解决方案。

关于c++ - 将标准容器传递给模板化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8072790/

相关文章:

c++ - 如何在不使用 const 的情况下防止删除指针?

c++ - 我们如何知道代码是线程安全的?

c++ - C++模板和鸭子类型(duck typing)有什么关系?

c++ - 从函数体中推导模板参数

.net - 程序集链接器错误故障排除,C++,VS 2005

c++ - SDL_BlitScaled 不起作用

C++捕获命令行逐行输入和输出

C++ void_t SFINAE false_type true_type 无法获得特化

c++ - 为 EventDriver 传递和存储模板函数指针

c++ - 在编译时初始化 c++ std::bitset