views:

166

answers:

2
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)

A: 

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.

Marcelo Cantos
Deriving a class template from another class has the problem that it becomes a different type, so any functions that take the base class would not work. With wrapping the class name into a struct, the type stays the same and acts just like a typedef i.e. it is the exact same type.
Akanksh
+9  A: 

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
Akanksh
Thanks! The wrapping method did the trick. I couldn't get the C++0x example working in gcc 4.4.1 using -std=c++0x. `template<typename T, typename S> typedef boost::interprocess::adaptive_pool<T, S> allocator_t;` gives `error: template declaration of 'typedef'`