你能做一个C ++通用函数吗? [英] Can you make a C++ generic function?

查看:168
本文介绍了你能做一个C ++通用函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建一个通用的C ++函数 foo

Is it possible to create a generic C++ function foo?

foo(Object bar, Object fred)
{
    //code
}

其中如果两个对象被识别,则比较它们并返回一个比较值,否则返回一些其他值以指示不可能进行比较。

in which that if the two objects are recognized, they are compared and a comparison value is returned otherwise some other value is returned to indicate a comparison was not possible?

我要求在泛化排序类的情况下,在这种情况下,您可以使用此方法,并且当您导出要对其排序的新对象时,您添加到此foo函数,一个方法来对新类型of Object。

I ask in the case of genericizing a sorting class, in which case you can use this method, and when you derive new objects you want to sort, you add to this foo function, a method on which to sort the new type of Object.

推荐答案

我认为你急需 模板

您可以编写一个模板函数,然后为所述类型写一个特殊化来做特定的事情需要。

I think you are in dire need of Templates!
You can write a template function and then write a specialization for the said types to do something specific if the need be.

这篇关于你能做一个C ++通用函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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