Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make a C++ generic function?

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?

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.

like image 491
SGE Avatar asked May 14 '12 07:05

SGE


2 Answers

Using templates, define two versions of the function, one where the parameters are the same type and one where they can be different:

#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;
}

Output:

same
different
different
same
like image 63
Peter Wood Avatar answered Oct 19 '22 13:10

Peter Wood


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.

like image 41
Alok Save Avatar answered Oct 19 '22 14:10

Alok Save