开发者

C++ When template argument deduction fails

Why can't C++ determine that I intend to create a unique_ptr<A> with this syntax? (a has previ开发者_如何学JAVAously been declared as unique_ptr<A>)

a = unique_ptr(new A());

It seems awfully redundant to have to include <A>. This works for most functions templates I use, why not unique_ptr?

EDIT: C++ now supports make_unique, with no redundancy.


std::unique_ptr is a class template, not a function template. Argument deduction only happens for function templates, not class templates.

A commonly used trick is to write a function template that creates an object of the instantiated class template type, for example:

template <typename T>
std::unique_ptr<T> make_unique_ptr(T* ptr) 
{
    return std::unique_ptr<T>(ptr);
}

For std::unique_ptr, though, I'd avoid doing this: a std::unique_ptr object should directly take ownership of the dynamically allocated object, so there should not be a need for this. Your code should either be written as:

std::unique_ptr<A> a(new A());

or, if a already exists, a call to reset() can be used:

a.reset(new A());

As for why type deduction won't work for instantiating a class template, consider the following example:

template <typename T>
struct X
{
    template <typename U> X(U) { }
};

There is no way that T could be deduced from an invocation of the constructor. Even in "simpler" cases where there is a constructor with a parameter of type T, there can still be trouble since constructors can be overloaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜