为什么不能推论unique_ptr的模板参数? [英] Why can't unique_ptr's template arguments be deduced?

查看:82
本文介绍了为什么不能推论unique_ptr的模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您可以从C ++ 17获得类模板参数推导时,为什么不能推导std :: unique_ptr的模板参数呢?例如,这给了我一个错误:

When you have class template argument deduction available from C++17, why can't you deduce the template arguments of std::unique_ptr? For example, this gives me an error:

std::unique_ptr smp(new D);

上面写着类模板的参数列表丢失。

That says "Argument list of class template is missing".

模板参数(至少是指针类型)不是可推论的吗?

Shouldn't the template arguments (at least the pointer type) be deducable?

请参阅以下内容


任何指定初始化的声明变量和
变量模板

any declaration that specifies initialization of a variable and variable template


推荐答案

我不再重复 @NathanOliver很好的答案中的基本原理,我只想提一下它的方法 ,力学,这也是我想你所追求的。没错,如果 unique_ptr 的构造函数看起来像......

I'm not going to repeat the rationale in @NathanOliver's great answer, I'm just going to mention the how of it, the mechanics, which is what I think you are also after. You are right that if the constructor of unique_ptr looked merely like...

explicit unique_ptr( T* ) noexcept;

...可以推断 T 。编译器生成的推导指南可以正常工作。就像Nathan所说明的那样,这将是一个问题。但是构造函数是这样指定的……

... it'd be possible to deduce T. The compiler generated deduction guide would work just fine. And that would be a problem, like Nathan illustrates. But the constructor is specified like this...

explicit unique_ptr( pointer p ) noexcept;

...其中别名 pointer 是指定如下:

... where the alias pointer is specified as follows:


指针 std ::如果存在该
类型,则为remove_reference< Deleter> :: type :: pointer
,否则为 T * 。必须满足 NullablePointer

pointer : std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*. Must satisfy NullablePointer.

该规范实质上意味着指针必须是 __ some_meta_function< T> :: type 的别名。 :: type 左侧的所有内容都是非推导上下文,这是防止从中推导 T 的原因。 指针。即使指针始终必须为 T * ,这也可以使这类推论指南失败。仅仅通过使其成为非推论上下文,就可以防止该构造函数生成的任何推论指南的可行性。

That specification essentially means that pointer must be an alias to __some_meta_function<T>::type. Everything on the left of ::type is a non-deduced context, which is what prevents the deduction of T from pointer. That's how these sort of deduction guides could be made to fail even if pointer needed to be T* always. Just by making it a non-deduced context will prevent the viability of any deduction guide produced from that constructor.

这篇关于为什么不能推论unique_ptr的模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆