代码之家  ›  专栏  ›  技术社区  ›  mch

模板类的typedef?

  •  7
  • mch  · 技术社区  · 17 年前

    可以吗 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 回复  |  直到 17 年前
        1
  •  14
  •   Leon Timmermans    17 年前

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

    我能想到的最好的是

    template<typename T> struct LongCollection {
        typedef std::vector< boost::shared_ptr< LongClassName<T> > > type;
    };
    
    LongCollection<float>::type m_foo;
    
        2
  •  3
  •   activout.se    17 年前

    如果不想按宏的方式执行,则必须为每种类型创建单独的typedef:

    typedef std::vector< boost::shared_ptr< LongClassName<float> > > FloatCollection;
    typedef std::vector< boost::shared_ptr< LongClassName<double> > > DoubleCollection;
    
        3
  •  2
  •   Rob Walker    17 年前

    不,但您可以使用“helper”类型接近,请参见 example .

        4
  •  2
  •   Konrad Rudolph    17 年前

    列昂给出的解是规范的。一点背景知识:这被称为一个_(模板)元函数_,因为它基本上是一个__函数_,在编译时被评估。它处理的不是值,而是类型:有一个输入类型列表(类型参数),还有一个__返回值_:声明类型名称__类型__的typedef。

    _156;invocation_157;的工作方式与正常函数调用类似,尽管使用了不同的语法:

    // Normal function
    result = f(args);
    
    // Metafunction
    typedef f<args>::type result;
    

    这种代码构造是一种常用的习惯用法,在诸如boost库之类的库中,甚至在STL中的一个位置上: allocator_type::rebind<U>::other 完成相同的事情,唯一的区别是typedef type 被称为 other .

        5
  •  1
  •   John Dibling    17 年前

    这并不完全是你想要的,但这可能会根据你的实际情况达到预期的效果:

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

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