If I am allowed to do the following:
template
class Foo{
};
Why am I not allowed to do the following in main?
You are not allowed to do that but you can do this
typedef Foo<> Fooo;
and then do
Fooo me;
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.
You can use the following:
Foo<> me;
And have int
be your template argument. The angular brackets are necessary and cannot be omitted.
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.