Creating a type alias for a templated class

后端 未结 3 1747
小鲜肉
小鲜肉 2020-12-31 16:35

Instead of using

std::vector ObjectArray;


I would like it to be

MyArray ObjectArray;

相关标签:
3条回答
  • 2020-12-31 16:51

    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.

    0 讨论(0)
  • 2020-12-31 17:03

    As of C++11 you can use a templated type alias

    template <typename T>
    using MyArray = std::vector<T>;
    

    If you want to be more generic you can use a variadic template (which would allow for allocators in the case of vector without having to be specific)

    template <typename... Ts>
    using MyArray = std::vector<Ts...>;
    
    0 讨论(0)
  • 2020-12-31 17:11

    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 讨论(0)
提交回复
热议问题