C++ 17指向tempalte类的指针,带有类模板参数

发布于 2025-02-10 08:54:02 字数 579 浏览 1 评论 0原文

我正在尝试C ++ 17类模板默认参数,并且想知道是否有人可以解释:

如果我有以下内容:

template<typename Policy = DefaultPolicy>
class MyClass { //class goes here };

然后尝试将其使用为:

MyClass * class = new MyClass();

我得到错误:

,这两个编译都可以:

MyClass stackClass = MyClass();

auto * heapClass = new MyClass();

但是 对自动在上面的工作非常感兴趣。非常感谢!

也许还有一个概念名称可以描述我可以Google以获取更多信息。

工作示例: https://godbolt.org/z/ebenxjcej

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

婴鹅 2025-02-17 08:54:02

正确的语法构成具有默认参数的模板实例指针的是:

MyClass<> * heapClass = new MyClass();  
auto smartClass = std::make_unique<MyClass<>>(); // for same reason

myClass正式不是类型ID,它是模板名称。这就是为什么make_unique会失败的原因,因为它的参数应为typename。指针声性语法将需要相同的语法。 auto做什么是使用完整的类型ID- myClass&lt; defaultPolicy&gt;
新表达式是C ++ 17中允许的特殊情况之一,以及myClass stackClass,尽管为Clarity 新的myClass&lt;()可以用作17年前。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文