模板类的typedef?

时间:2008-10-30 19:30:52

标签: c++ templates typedef

是否可以typedef使用模板的长类型?例如:

template <typename myfloat_t>
class LongClassName
{
    // ...
};

template <typename myfloat_t>
typedef std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > LongCollection;

LongCollection<float> m_foo;

这不起作用,但有没有办法达到类似效果?我只想避免键入和读取几乎涵盖编辑器窗口全宽的类型定义。

5 个答案:

答案 0 :(得分:14)

不,目前不可能。它将在C ++ 0X AFAIK中实现。

我能想到的最好的是

template<typename T> struct LongCollection {
    typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
};

LongCollection<float>::type m_foo;

答案 1 :(得分:3)

如果您不想采用宏方式,则必须为每种类型创建单独的typedef:

typedef std::vector< boost::shared_ptr< LongClassName<float> > > FloatCollection;
typedef std::vector< boost::shared_ptr< LongClassName<double> > > DoubleCollection;

答案 2 :(得分:2)

不,但您可以使用'帮助'类型来结束,请参阅此example

答案 3 :(得分:2)

莱昂所展示的解决方案是规范的。一点背景知识:这被称为“(模板)元函数”,因为它基本上是一个在编译时得到评估的“函数”。它代替值,它处理类型:有一个输入类型列表(类型参数),还有一个“返回值”:typedef声明类型名称“type”。

“调用”与普通函数调用类似,尽管语法不同:

// Normal function
result = f(args);

// Metafunction
typedef f<args>::type result;

这个代码构造是库中常用的习惯用法,例如Boost库,甚至在一个地方的STL中:allocator_type::rebind<U>::other完成同样的事情,唯一的区别是typedef type是叫other

答案 4 :(得分:1)

它并不完全符合您的要求,但根据您的实际情况,这可能会达到预期的效果:

template <typename myfloat_t>
class LongClassName
{
    // ...
};

template <typename myfloat_t>
class LongCollection : public std::vector< boost::shared_ptr< LongClassName<myfloat_t> > > 
{
};

您可能需要根据需要添加一些构造函数或运算符。