Template Alias with Default Value
Asked Answered
N

1

7

Info

I am trying to use a template alias to improve the readabilty of my code. Ideally I would like to the alias to have a default argument such that if I leave out the template it uses the default (exactly with template functions and template classes).

The code would look like

template<typename T = double>
struct mystruct {};

template<typename T = double> using myalias = mystruct<T>;

int main(void) {

    myalias MyStructWithDouble; // causes compilation error
    myalias<int> MyStructWithInt;

    return 0;
}

The compiler (g++ 4.7 in this case) is quite happy with the inclusion of the = double in the alias definition but it seems to then ignore this.

I tried something like "specializing" the alias as well but there the compiler baulked.

Question

Why does the compiler accept the default in the defintion if we are not allowed to use it? Secondly, is there a way of acheiveing this?

Motivation

This example is very simple but in my real code the alias would save a lot of typing (there are more than one template parameter)

Neo answered 2/7, 2013 at 10:19 Comment(0)
L
13

Just like with class templates, you still need to supply an empty template argument list:

myalias<> MyStructWithDouble; // compiles
Leninism answered 2/7, 2013 at 10:22 Comment(5)
Could you elaborate why this is the case? If I were to create this directly from mystruct I can simply type mystruct MyStructWithDouble;?Neo
@Dan: No you can't, at least not without a nonstandard compiler extension. For example, GCC says error: invalid use of template-name ‘mystruct’ without an argument listLeninism
My mistake. Is there any reason for this? Can the compiler not tell that myalias means the same as myalias<>? And is there some way to "cheat" this behaviour from the compiler?Neo
@Dan: I don't think so, unfortunately. It's probably for the same reason that you need to say f() when calling a no-argument function f: the name without the parentheses refers to the function itself. Similarly, the name of a template without a (possibly empty) parameter list refers to the template itself (so you can pass it as a template template parameter), whereas the name with the angle brackets denotes an instantiation of said template.Leninism
Nice analogy. That makes sense. It just means my code won't be as clean as I would like, oh well.Neo

© 2022 - 2024 — McMap. All rights reserved.