你能做一个C++泛型函数吗?

SGE*_*SGE 11 c++ sorting oop generics object

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

foo(Object bar, Object fred)
{
    //code
}
Run Code Online (Sandbox Code Playgroud)

如果识别出两个对象,则比较它们并返回比较值,否则返回一些其他值以表示无法进行比较?

我要求在对排序类进行泛化的情况下,在这种情况下,您可以使用此方法,并且在派生要排序的新对象时,可以添加到此foo函数,该方法用于对新类型的Object进行排序.

Pet*_*ood 28

使用模板定义函数的两个版本,一个是参数类型,另一个是不同的版本:

#include <string>
#include <iostream>
using namespace std;

template<typename Type>
void func(Type, Type)
{
    cout << "same" << endl;
}

template<typename TypeA, typename TypeO>
void func(TypeA, TypeO)
{
    cout << "different" << endl;
}

int main()
{
    func(5, 3);                     // same
    func(5, 3.0);                   // different
    func(string("hello"), "hello"); // different
    func(5.0, 3.0);                 // same
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

same
different
different
same
Run Code Online (Sandbox Code Playgroud)


Alo*_*ave 18

我认为你急需模板!
您可以编写模板函数,然后为所述类型编写专门化,以便在需要时执行特定操作.


moh*_*aps 5

template<class Type1, class Type2>
void foo(Type1 t1, Type2 t2)
{
   // put code here for function
}
Run Code Online (Sandbox Code Playgroud)

打电话给

foo<std::string, int> ("hello", 10);
Run Code Online (Sandbox Code Playgroud)