使用模板时的类型推断 [英] type inference when using templates

查看:132
本文介绍了使用模板时的类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是我想做的:我使用 std :: pair ,但我一定会喜欢做同样使用元组,或者几乎任何种类的模板。当分配一个对变量时,我需要输入如下:

So here is what I would like to do: I use std::pair, but I would surely like to do the same using tuples, or indeed pretty much any kind of template. When assigning a pair variable, I need to type something like:

T1 t1;
T2 t2;
std::pair<T1,T2> X;
X = std::pair<T1,T2> (t1, t2);

有没有办法省略第二个< T1,T2& / code>创建一个新对,并让编译器猜测,使用X的类型(我显然是试图创建一个对< T1,T2> )或 t1 t2 的类型(我正在构建一个 / code>对象和 T2 对象,有一个机会,我想要的对类型 pair< T1,T2> code>)?

Is there a way to omit the second <T1,T2> when creating the new pair, and let the compiler guess, either using X's type (I'm obviously trying to create a pair<T1,T2>) or t1 and t2's types (I am building a pair with a T1 object and a T2 object, there is a chance the pair I want is of type pair<T1,T2>) ?

推荐答案

是的,但模板参数扣除只适用于函数模板,而不适用于类模板的构造函数。因此,库提供了一个函数:

Yes, but template argument deduction only works on function templates, not constructors of class templates. For this reason, the library provides a function:

X = std::make_pair(t1, t2);

在C ++ 11中,对和元组可以初始化并从初始化器列表中分配:

In C++11, pairs and tuples can be initialised and assigned from initialiser lists:

X = {t1, t2};

auto 类型从初始化程序,所以你不需要指定模板参数:

or auto can be used to automatically specify the type from the initialiser, so you don't need to specify the template arguments at all:

auto X = std::make_pair(t1, t2);

这篇关于使用模板时的类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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