c++templatesusing-declaration

Can `using` work without specifying template parameters?


Is it possible to use using with a template class without specifying its template parameters straight away?

#include <array>
    
using MyArray = std::array<int, 5>;
using MyArrayT = std::array;         // error: missing template arguments after 'std::array'
    
int main() {
    
    MyArray myArray1;
    MyArrayT<char, 10> myArray2;
}

P.S.: Without using preprocessor tricks...


Solution

  • You cannot do it like that because a "normal" type alias (using statement) is aliasing a concrete type with a new name, and std::array is not a concrete type.

    But you can make the type alias itself templated (syntax (2)):

    #include <cstddef>  // for std::size_t
    #include <array>
    
    template <typename T, std::size_t N>
    using MyArrayT = std::array<T, N>;            
    

    Then use it like you attempted:

    MyArrayT<char, 10> myArray2;
    

    Live demo