Why can't unique_ptr's template arguments be deduced?

我的未来我决定 提交于 2020-06-21 17:09:47

问题


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?

See this:

any declaration that specifies initialization of a variable and variable template


回答1:


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;

... 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;

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

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

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.




回答2:


Lets look at new int and new int[10]. Both of those return an int*. There is no way to tell if you should have unique_ptr<int> or unique_ptr<int[]>. That right there is enough not to provide any sort of deduction guide.



来源:https://stackoverflow.com/questions/51109767/why-cant-unique-ptrs-template-arguments-be-deduced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!