c++ - 根据模板参数包装类型容器的模板类

标签 c++ templates specialization

我想要一个包装容器的模板类,但我想根据模板参数的值来选择包装哪个容器。 像这样的东西:

template<typename T>
class A{
  std::vector<T> MyContainer;
  // ...
}

template<>
class A<bool>{
  std::deque<bool> MyContainer;
  // ...
}

但避免了模板特化涉及的所有代码重复。我试图看看 std::enable_if 是否可以帮助我做一些技巧,但我还没有想出任何办法。

最佳答案

可以使用std::conditional作为Nawaz said :

#include <type_traits>

template <typename T>
using MyContainerType = typename std::conditional<
                        std::is_same<T, bool>::value,
                        std::deque<T>,
                        std::vector<T>
                        >::type ;

template<typename T>
class A{
  //std::vector<T> MyContainer;
  // ...
    MyContainerType<T> C;
} ;

关于c++ - 根据模板参数包装类型容器的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26699285/

相关文章:

c++ - 对模板感到困惑

c++ - C++ 中基于类型的模板函数

C++ 专门针对枚举的函数

c++ - 运算符 << 的两阶段查找

c++ - 对 glfwSetErrorCallback 的 undefined reference

c++ - 在 C++ 中使用 #include 包含多个

c++ - char (& test(...))[2] 是什么意思

php - Codeigniter - 让我的 Controller 更干

rust - 特质特化实际上是如何运作的?

c++ - 向 pthread 函数传递和访问多个参数