porgarmingduod
porgarmingduod

Reputation: 7878

Alias for a C++ template?

typedef boost::interprocess::managed_shared_memory::segment_manager 
    segment_manager_t; // Works fine, segment_manager is a class
typedef boost::interprocess::adaptive_pool
    allocator_t; // Can't do this, adaptive_pool is a template

The idea is that if I want to switch between boost interprocess' several different options for shared memory and allocators, I just modify the typedefs. Unfortunately the allocators are templates, so I can't typedef the allocator I want to use.

Is there a way to achieve an alias to a template in C++? (Except for the obvious #define ALLOCATOR_T boost::interprocess::adaptive_pool)

Upvotes: 6

Views: 6603

Answers (2)

Akanksh
Akanksh

Reputation: 1300

Yes, (if I understand your question correctly) you can "wrap" the template into a struct like:

template<typename T>
class SomeClass;

template<typename T>
struct MyTypeDef
{
    typedef SomeClass<T> type;
};

and use it as:

MyTypeDef<T>::type

Edit: C++0x would support something like

template<typename T>
using MyType = SomeClass<T>;

Edit2: In case of your example

typedef boost::interprocess::adaptive_pool allocator_t;

can be

template<typename T>
struct allocator_t
{
    typedef boost::interprocess::adaptive_pool<T> type;
}

and used as

allocator_t<SomeClass>::type

Upvotes: 17

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

C++ doesn't support this, though it is slated to be fixed in the new standard. You might get away with deriving a new class template from adaptive_pool if there are no non-trivial constructors (or if you're happy to write a few forwarding constructors).

template <class T>
class allocator_t : public adaptive_pool<T> {
public:
    // Just making up a forwarding constructor as an example. I know nothing
    // anything about adaptive_pool.
    allocator_t(int arg1, float arg2) : adaptive_pool<T>(arg1, arg2) { }
};

EDIT: Forget this answer. My vote goes to @Akanksh.

Upvotes: 1

Related Questions