Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template default arguments

Tags:

c++

templates

Note:

Foo me; without template arguments is legal as of C++17. See this answer: https://stackoverflow.com/a/50970942/539997.

Original answer applicable before C++17:

You have to do:

Foo<> me;

The template arguments must be present but you can leave them empty.

Think of it like a function foo with a single default argument. The expression foo won't call it, but foo() will. The argument syntax must still be there. This is consistent with that.


With C++17, you can indeed.

This feature is called class template argument deduction and add more flexibility to the way you can declare variables of templated types.

So,

template <typename T = int>
class Foo{};

int main() {
    Foo f;
}

is now legal C++ code.


You are not allowed to do that but you can do this

typedef Foo<> Fooo;

and then do

Fooo me;

You can use the following:

Foo<> me;

And have int be your template argument. The angular brackets are necessary and cannot be omitted.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!