C++模板的别名?

por*_*uod 6 c++ templates typedef

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
Run Code Online (Sandbox Code Playgroud)

我的想法是,如果我想在boost进程之间切换共享内存和分配器的几个不同选项,我只需要修改typedef.不幸的是,分配器是模板,所以我不能键入我想要使用的分配器.

有没有办法在C++中实现模板的别名?(除了显而易见的#define ALLOCATOR_T boost::interprocess::adaptive_pool)

Aka*_*ksh 17

是的,(如果我理解你的问题)你可以将模板"包装"成一个结构,如:

template<typename T>
class SomeClass;

template<typename T>
struct MyTypeDef
{
    typedef SomeClass<T> type;
};
Run Code Online (Sandbox Code Playgroud)

并将其用作:

MyTypeDef<T>::type
Run Code Online (Sandbox Code Playgroud)

编辑:C++ 0x会支持类似的东西

template<typename T>
using MyType = SomeClass<T>;
Run Code Online (Sandbox Code Playgroud)

Edit2:如果是你的例子

typedef boost::interprocess::adaptive_pool allocator_t;
Run Code Online (Sandbox Code Playgroud)

template<typename T>
struct allocator_t
{
    typedef boost::interprocess::adaptive_pool<T> type;
}
Run Code Online (Sandbox Code Playgroud)

并用作

allocator_t<SomeClass>::type
Run Code Online (Sandbox Code Playgroud)