2014-11-02 142 views
0

我想要一个包装容器的模板类,但我想根据模板参数的值选择要包装哪个容器。 喜欢的东西:根据模板参数包装类型容器的模板类

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

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

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

+1

什么简单地提供容器类型作为另一个(依赖)模板参数? – 2014-11-02 12:28:53

+0

我不知道你的例子是否真实,但你必须知道'std :: vector '在STLibrary中已经不同了。 – Caduchon 2014-11-02 12:35:40

+1

@πάνταῥεῖ这太难看了。这个班的使用者不需要照顾那个。这是班级的业务,那么班级应该照顾它。 – Kae 2014-11-02 12:35:42

回答

3

你可以这样做:

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

reference

或者可以编写自己:

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; 
}; 
+4

在C++标准库中,你有'std :: conditional',可以用来代替'mpl :: if_c'。 – Nawaz 2014-11-02 12:37:12

+0

这适用于我。等待5分钟。 Nawaz的评论很好,所以我不必使用Boost。 – Kae 2014-11-02 12:37:57

+0

@Nawaz哇不记得标准的人叫什么了。谢谢。 – Barry 2014-11-02 12:48:49

4

可以使用std::conditionalNawaz 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; 
} ; 
+0

Demo [_'here'_](http://rextester.com/OAP23715) – P0W 2014-11-02 12:52:53

+1

顺便说一句,现在你可以使用'std :: is_same {}'而不是'std :: is_same :: value'。 C++ 14已由GCC和Clang完全实现。 – Nawaz 2014-11-02 13:41:44

相关问题