Thursday, March 31, 2011

C++: typedef-ing STL

Instead of using

std::vector<Object> ObjectArray;

I would like it to be

MyArray<Object> ObjectArray;

with all the std::vector methods preserved. (like push_back(), reserve(), ...etc)

However, using

typedef std::vector MyArray;

won't work. Should I use template instead? How?

Thanks in advance.

From stackoverflow
  • What you would really want is a templated typedef. Unfortunately those are not supported in the current version of C++, but they will be added in C++0x.

    For now, here's a possible workaround:

    template<class T> struct My {
        typedef std::vector<T> Array;
    };
    
    My<Object>::Array ObjectArray
    

    Whether or not that is better than simply using std::vector directly, I'll leave to you to decide.

    Thomas : Greg, thanks for fixing my syntax. Can you tell that I've been using a lot of Java lately? ;)
    spoulson : Clever use of metaprogramming.
  • Another way:

    #include <vector>
    
    template <typename T>
    struct MyArray
        :std::vector<T>
    {
    };
    
    void func()
    {
        MyArray<int> my;
    
        my.push_back(5);
    
        MyArray<int>::iterator i;
    }
    

    Compiles for me, but you may find that some things available in vector<> need to be "pulled up" into MyArray.

0 comments:

Post a Comment