C++ 当模板参数推导失败时 [英] C++ When template argument deduction fails

查看:34
本文介绍了C++ 当模板参数推导失败时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 C++ 不能确定我打算用这种语法创建一个 unique_ptr<A>?(a 之前已声明为 unique_ptr)

Why can't C++ determine that I intend to create a unique_ptr<A> with this syntax? (a has previously been declared as unique_ptr<A>)

a = unique_ptr(new A());

必须包含 似乎非常多余.这适用于我使用的大多数函数模板,为什么不使用 unique_ptr?

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

C++ 现在支持 make_unique,没有冗余.

C++ now supports make_unique, with no redundancy.

推荐答案

std::unique_ptr 是一个 class 模板,而不是一个 function模板.参数推导只发生在 function 模板,而不是 class 模板.

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);
}

对于 std::unique_ptr,不过,我会避免这样做:std::unique_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());

或者,如果 a 已经存在,可以使用对 reset() 的调用:

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) { }
};

T 不可能从构造函数的调用中推导出来.即使在有一个带有 T 类型参数的构造函数的更简单"的情况下,仍然会出现问题,因为构造函数可能会被重载.

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.

这篇关于C++ 当模板参数推导失败时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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