Reputation: 21
I am experimenting with C++17 class template default argument and was wondering if anyone could explain:
If I have the following:
template<typename Policy = DefaultPolicy>
class MyClass { //class goes here };
And then try to use it as:
MyClass * class = new MyClass();
I get the error:
However both the following compile OK:
MyClass stackClass = MyClass();
auto * heapClass = new MyClass();
In particular I am very interested in how auto is working above. Thanks so much!
Perhaps there is also a concept name that describes this that I can google for more info also.
Working example: https://godbolt.org/z/EbEnxjcej
Upvotes: 0
Views: 58
Reputation: 14589
Correct syntax forming a pointer to a template instance with default parameter would be:
MyClass<> * heapClass = new MyClass();
auto smartClass = std::make_unique<MyClass<>>(); // for same reason
MyClass
formally isn't a type-id, it's a template name. That's why make_unique
would fail, because its parameter should be a typename
. Pointer declaration syntax would require same. What auto
does is use of a full type-id - MyClass<DefaultPolicy>
.
The new expression is one of special cases allowed in C++17 along with MyClass stackClass
although for clarity new MyClass<>()
can be used as pre-17.
Upvotes: 2