Question

Is it possible to typedef long types that use templates? For example:

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

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

LongCollection<float> m_foo;

This doesn't work, but is there a way to achieve a similar effect? I just want to avoid having to type and read a type definition that covers almost the full width of my editor window.

Was it helpful?

Solution

No, that isn't possible currently. It will be made possible in C++0X AFAIK.

The best I can think of is

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

LongCollection<float>::type m_foo;

OTHER TIPS

If you don't want to go the macro way you have to make individual typedefs for each type:

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

No, but you can get close using a 'helper' type, see this example.

The solution shown by Leon is canonical. Bit of background knowledge: This is called a “(template) metafunction” because it is basically a “function” that gets evaluated at compile time. Instead of values, it deals with types: There's a list of input types (the type arguments) and there's a “return value”: The typedef that declares the type name “type”.

“Invocation” works analogously to normal function invocation, albeit with a different syntax:

// Normal function
result = f(args);

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

This code construct is an often-used idiom in libraries such as the Boost libraries and even in the STL at one place: allocator_type::rebind<U>::other accomplishes the same thing with the only difference that the typedef type is called other.

Its not exactly what you're asking for, but this might achieve the desired effect depending on your actual situation:

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

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

You may need to add some constructors or operators depending on your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top