C++: Why is the recursive templated alias forbidden?

Viewed 167

Why is this fails to compile:

template<typename T, int N>
using vec = vector<vec<T, N - 1>>;
template<typename T>
using vec<0> = T;

while just nesting it into a struct works just fine:

template<typename T, int N>
struct foo {
    using vec = vector<typename foo<T, N - 1>::vec>;
};
template<typename T>
struct foo<T, 0> {
    using vec = T;
};

What is the rationale for forbidding recursion in aliases if you can just replace it with more verbose construct?

see: https://godbolt.org/g/YtyhvL

1 Answers

What is the rationale for forbidding recursion in aliases if you can just replace it with more verbose construct?

You kinda answered your own question there. You have the mechanism to do what you want. And since an alias by definition is meant to be just a shorthand for something, why complicate the languages already complicated grammar?

You use the structure to implement the machinery, and an alias to give the nice type name:

template<typename T, int N>
using vec = typename foo<T,N>::vec;

Short and sweet, and with a simpler language grammar.

Related