调用无<&gt ;;的模板函数类型推断 [英] Calling template function without <>; type inference

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

问题描述

如果我有一个具有 typename T 的函数模板,其中编译器可以自己设置类型,我不必在调用函数时显式地写类型例如:

If I have a function template with typename T, where the compiler can set the type by itself, I do not have to write the type explicitly when I call the function like:

template < typename T > 
T min( T v1, T v2 ) {
   return ( v1 < v2 ) ? v1: v2;
}
int i1 = 1, i2 = 2; int i3 = min( i1, i2 ); //no explicit <type> 

但是如果我有一个包含两个不同类型名的函数模板:

But if I have a function template with two different typenames like:

template < typename TOut, typename TIn >
TOut round( TIn v ) {
   return (TOut)( v + 0.5 );
}
double d = 1.54;
int i = round<int>(d); //explicit <int>

这是真的,我总是要指定至少1个typename?我假设原因是因为C ++不能区分不同返回类型之间的函数。

Is it true that I always have to specify at least 1 typename? I assume the reason is because C++ can not distinguish functions between different return types.

但是如果我使用void函数和切换引用,我再也不必明确指定return typename:

But if I use a void function and handover a reference, again I must not explicitly specify the return typename:

template < typename TOut, typename TIn > 
void round( TOut & vret, TIn vin ) {
   vret = (TOut)(vin + 0.5);
}
   double d = 1.54;
   int i; round(i, d); //no explicit <int>

应该结论是避免函数返回和更喜欢 void 在编写模板时通过引用返回的函数?还是有可能避免明确写入返回类型?类似模板的类型推断。是否可以在C ++ 0x中进行类型推断?

Should the conclusion be to avoid functions with return and more prefer void functions that return via a reference when writing templates? Or is there a possibility to avoid explicitly writing the return type? Something like "type inference" for templates. Is "type inference" possible in C++0x?

推荐答案

重载解析只基于函数参数;则不使用返回值。如果无法根据参数确定返回类型,则必须明确指定它。

Overload resolution is done only based on function arguments; the return value is not used at all. If the return type cannot be determined based on the arguments, you will have to specify it explicitly.

我不会沿着返回一个值的路径通过参考参数;这使得调用代码不清楚。例如,我更喜欢这样:

I would not go down the path of "returning" a value through a reference parameter; that makes the calling code unclear. For example, I'd prefer this:

double x = round<double>(y);

double x;
round(x, y);

因为在后一种情况下,很容易混淆输入和输出, x 正在修改。

because in the latter case, it's easy to confuse input and output, and it's not at all clear that x is being modified.

c>,你可能只需要一个或两个类型 TOut ,所以你可以离开模板参数:

In the particular case of round, you probably need only one or two types for TOut anyway, so you could just leave that template argument out:

template<typename TIn>
int roundToInt(TIn v) {
    return (int)(v + 0.5);
}

我找到 roundToInt(x) round< int>(x)有一点清楚,因为它清楚了 int

I find roundToInt(x) a little clearer than round<int>(x) because it's clear what the int type is used for.

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

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