Reputation: 16324
In my c++ template struct I want to use different container types which use different allocators, e.g. std::vector and thrust::device_vector.
I need to specify the allocator explicitely, otherwise I get "wrong number of template arguments (1, should be 2)":
template<typename T, template <typename, typename> class Container, typename Alloc>
struct wrap_into_container
{
typedef Container<T, Alloc> type;
};
Since the different container classes use different allocators, I have to specify the corresponding allocator everytime I want to use this template.
How can I get the allocator depending on the Container type without having to specify it?
I thought of using a traits struct which I then specialize for each Container type, but I don't know how to implement it or if it is even useful / possible / ...
UPDATE: I cannot use C++11 unfortunately due to restrictions of the NVIDIA compiler ...
Upvotes: 3
Views: 2688
Reputation: 392863
In c++11, I favour variadics
template<typename T, template <typename...> class Container>
struct wrap_into_container
{
typedef Container<T>::type type;
};
(I haven't checked whether C::type
is actually a wellformed expression for standard container types)
To the comment:
template<typename T, template <typename...> class Container>
struct wrap_into_container
{
typedef Container<T>::type type;
};
For C++03 you can emulate a template alias using nested typedefs, essentially making a unary type-function taking a single element type and returning a container of that type. The concept:
#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();
}
See it Live On Coliru
Upvotes: 6