Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 根据模板参数包装类型为的容器的模板类_C++_Templates_Specialization - Fatal编程技术网

C++ 根据模板参数包装类型为的容器的模板类

C++ 根据模板参数包装类型为的容器的模板类,c++,templates,specialization,C++,Templates,Specialization,我希望有一个包装容器的模板类,但我希望根据模板参数的值选择包装哪个容器。 比如: template<typename T> class A{ std::vector<T> MyContainer; // ... } template<> class A<bool>{ std::deque<bool> MyContainer; // ... } 但是避免了模板专门化所涉及的所有代码重复。我想看看std::enable_

我希望有一个包装容器的模板类,但我希望根据模板参数的值选择包装哪个容器。 比如:

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

template<>
class A<bool>{
  std::deque<bool> MyContainer;
  // ...
}
但是避免了模板专门化所涉及的所有代码重复。我想看看std::enable_if是否能帮我做一些小动作,但我还没有想出任何办法。

你可以做:

typedef typename boost::mpl::if_c<
    std::is_same<T, bool>::value,
    std::deque<T>,
    std::vector<T>
>::type MyContainerType;

或者你可以自己写:

typedef typename ContainerSelector<T>::type MyContainerType;
其中:

template <typename T>
struct ContainerSelector {
    typedef std::vector<T> type;
};

template <>
struct ContainerSelector<bool> {
    typedef std::deque<bool> type;
};
可以用作:


简单地提供容器类型作为另一个依赖模板参数怎么样?我不知道您的示例是否真实,但您必须知道std::vector在STLibrary中已经不同了。@πάνταῥεῖ 那太难看了。该类的用户不必处理这个问题。这是类的事务,然后类应该注意它。@ Caduchon,正是这个原因,我不想使用STD::在这种情况下,向量。在C++标准库中,你有STD::条件,它可以用来代替MPL::IFI.C.这对我有效。等5分钟。纳瓦兹的评论很好,所以我不必使用Boost。@Nawaz-wow记不起std的名字了。谢谢。顺便说一下,现在您可以使用std::is__same{}而不是std::is_same::value。C++14是由GCC和Clang完全实现的。
#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;
} ;