Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Alias with Default Value

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)

like image 271
Dan Avatar asked Jul 02 '13 10:07

Dan


1 Answers

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

myalias<> MyStructWithDouble; // compiles
like image 132
JohannesD Avatar answered Oct 08 '22 01:10

JohannesD