m.s*_*.s. 2 c++ containers templates stl
在我的c ++模板结构中,我想使用不同的容器类型,它们使用不同的分配器,例如std :: vector和thrust :: device_vector.
我需要明确指定分配器,否则我得到"错误的模板参数数量(1,应该是2)":
template<typename T, template <typename, typename> class Container, typename Alloc>
struct wrap_into_container
{
typedef Container<T, Alloc> type;
};
Run Code Online (Sandbox Code Playgroud)
由于不同的容器类使用不同的分配器,因此每次我想使用此模板时都必须指定相应的分配器.
如何根据Container类型获取分配器而不必指定它?
我想过使用traits结构,然后我专门为每个Container类型,但我不知道如何实现它,或者它是否有用/可能/ ...
更新:遗憾的是,由于NVIDIA编译器的限制,我无法使用C++ 11 ...
在c ++ 11中,我赞成variadics
template<typename T, template <typename...> class Container>
struct wrap_into_container
{
typedef Container<T>::type type;
};
Run Code Online (Sandbox Code Playgroud)
(我没有检查是否C::type实际上是标准容器类型的表达式)
评论:
template<typename T, template <typename...> class Container>
struct wrap_into_container
{
typedef Container<T>::type type;
};
Run Code Online (Sandbox Code Playgroud)
对于C++ 03,您可以使用嵌套的typedef模拟模板别名,实质上使得一元类型函数采用单个元素类型并返回该类型的容器.这个概念:
#include <vector>
#include <deque>
#include <set>
#include <list>
namespace container
{
template <typename T> struct vector { typedef std::vector<T> type; };
template <typename T> struct set { typedef std::set <T> type; };
template <typename T> struct list { typedef std::list <T> type; };
template <typename T> struct deque { typedef std::deque <T> type; };
}
template<typename T, template <typename> class Container>
struct wrap_into_container
{
typedef typename Container<T>::type type;
};
#include <string>
int main() {
wrap_into_container<int, container::set>::type ws;
wrap_into_container<double, container::list>::type wl;
wrap_into_container<bool, container::deque>::type wd;
wrap_into_container<std::string, container::vector>::type wv;
return ws.size() + wl.size() + wd.size() + wv.size();
}
Run Code Online (Sandbox Code Playgroud)