4

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

Dan M.
  • 3,410
  • 1
  • 20
  • 34

1 Answers1

2

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.

StoryTeller - Unslander Monica
  • 148,497
  • 21
  • 320
  • 399
  • Thanks, for some reason the though of using the templated alias for the nested one didn't occur to me) Still, I don't see how this will complicate the grammar in any major way. There are already template aliases. The syntax is there and it is the same as for the regular templates (so programmers are already used to it). One thing left is to add a specialization and allow recursion, and there won't be any need for hacks like in this case. – Dan M. Oct 05 '17 at 22:36
  • 1
    @DanM. - For a feature to be added to the standard, it must be demonstrated as useful. An alias is obviously useful. An alias specialization is not. Aliases were not added to take over from class templates. Plus their much more limited use makes their verification a whole lot simpler. – StoryTeller - Unslander Monica Oct 05 '17 at 22:53
  • @StorryTeller but why introduce alias templates then? By the same logic, you could just use `typename foo::vec` instead. – Dan M. Oct 06 '17 at 12:40
  • @DanM. - Not quite the same logic. [Properly using the typename and template keywords is less than easy to remember](https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords). Meta-programming library writes either had to provide their libraries as is, with the user dependent on the verbose syntax, or provide macros. But a macro is bad since it doesn't respect scope, or the type system. The marginal profit of aliases is worth it, since it is better than the above. But once you start replicating the rules for specializing, not so much worth it – StoryTeller - Unslander Monica Oct 06 '17 at 18:29