0

I want to define multidimensional array with the help of variadic template as vector<vector<....>>, but stumbled upon impossibility to define type initializer_list<initializer_list<...>>, which is needed for initializer-list-constructor. This briefly can be demonstrated by the following code

template<class T, size_t dim>
class MyArr : vector < MyArr < T, dim - 1 >>
{
public:
    typedef initializer_list<MyArr < T, dim - 1 >::ListType> ListType;
    //using ListType = typename initializer_list<MyArr < T, dim - 1 >::ListType>;
};

template<class T>
class MyArr<T, 1> : vector < T>
{
public:
    typedef initializer_list<T> ListType;
};

Compiler displays "error C2923: 'std::initializer_list' : 'MyArr::ListType' is not a valid template type argument for parameter '_Elem'".

What is the right way to define ListType type? Thanks for answers.

Alex B.
  • 348
  • 2
  • 12

1 Answers1

5

Everything behind MyArr<T, dim - 1>:: is a dependent-name, since both T and dim are template parameters, thus, a typename keyword is necessary to indicate it is a type.

template<class T, size_t dim>
class MyArr : vector < MyArr < T, dim - 1 >>
{
public:
    typedef initializer_list<typename MyArr < T, dim - 1 >::ListType> ListType;
    //                       ^^^^^^^^
};

or:

template<class T, size_t dim>
class MyArr : vector < MyArr < T, dim - 1 >>
{
public:
    using ListType = initializer_list<typename MyArr < T, dim - 1 >::ListType>;
    //                                ^^^^^^^^
};
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
  • Yes, this works, thanks a lot. Still I don't understand the logic behind the placement of `typename`. – Alex B. Sep 12 '14 at 21:09
  • @AlexB. It comes immediately before something that you know is going to be a type, but that the compiler can't infer must be a type. For example, if you specialized `MyArr` to have a `static int ListType` then in `MyArr`, `MyArr` would not name a type. Since `T` isn't known yet it doesn't know for sure if `ListType` is going to be a type. You put `typename` before the whole thing to hint to the compiler that it should assume that it will be a type. – cdhowie Sep 12 '14 at 21:15
  • I don't see how the compiler can deduce `dim - 1`? – David G Sep 12 '14 at 21:17