灵活返回类型的C ++功能模板 [英] C++ Function Template With Flexible Return Type

查看:119
本文介绍了灵活返回类型的C ++功能模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个像这样的函数

Let's say that we have a function like so

template <class T, class T2>
T getMin(T a, T2 b) {
  if(a < b)
    return a;
  return b;
}

如果我们调用这样的函数

if we call the function like so

int a, b;
long c;

a = getMin(b, c);

如果c是< a,那么c的值将被类型转换为int。

if c is < a, then the value of c will be type casted to int.

可以使返回类型灵活,以便返回int或long,任何其他类型被认为较小的<而不是类型转换?

Is it possible to make the return type flexible so that it would return an int, or long, or any other type considered smaller by "<" without being type casted?

编辑:
函数中涉及的类型可以是从简单类型到复杂类的任何类型,其中typecasting有时将是不可能的。

edit : the type involved in the function can be anything from simple type to complex classes where typecasting sometime won't be possible.

推荐答案

C ++ 0x将允许您使用 auto 关键字以便让编译器得到表达式的返回时间。

C++0x will allow you to use the auto keyword in order to let the compiler derive the return time of an expression.

对于C ++ 03,自动化这种过程是定义一个定义两种类型之间最强类型的模板类 Promotion ,然后专门用于您可能需要使用的几种类型。

For C++03 the only way I found to automatize such process is to define a template class Promotion that defines the strongest type between two types, and then specialize it for any couple of types you might need to use.

template<> class Promotion< long, int > { typedef long strongest; }
template<> class Promotion< int, long > { typedef long strongest; }

,因此:

template< typename T1, typename T2 >
Promotion<T1,T2>::strongest function( const T1 &a, const T2 &b ) { ... }

如果您选择尝试此解决方案,我建议使用自动生成的头文件生成Promotion特色。

If you choose to try this solution, I'd suggest to generate the Promotion specializations with an automatically generated header file.

编辑:在读取另一个(现已删除的)答案后重读问题:

I reread the question after reading the other (now deleted) answer:

您不能返回类型较小的变量。这是因为变量的值只能在运行时找到,而函数返回类型必须在编译时定义。

You can't return the type of the smaller variable. That's because the value of the variables will only be found out at runtime, while your function return type must be defined at compile time.

我提出的解决方案将总是返回两个变量类型之间的最强类型。

The solution I proposed will return always the strongest type between the two variables' type.

这篇关于灵活返回类型的C ++功能模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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