0

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

  • not related to your issue: `MyClass * class = new MyClass();` This is very bad. Don't use manual memory management in C++ (`new`, `delete`). Use smart pointers. – bolov Jun 23 '22 at 10:29
  • Yes, a similar issues occurs. I was hoping an explanation would explain this also: https://godbolt.org/z/KcP1xjahq – Marcus Raty Jun 23 '22 at 10:31

1 Answers1

2

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.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
  • Thank you! This explains it really well. I guess this is a short coming of template based policy design, it isn't very friendly in the user code. – Marcus Raty Jun 23 '22 at 12:35
  • @MarcusRaty it's inescapable, afaik. There are context where a template name can be used and it should be distinguished from type name. It's possible to have `template – Swift - Friday Pie Jun 24 '22 at 08:13