Can you make a C++ generic function?

前端 未结 7 1291
轮回少年
轮回少年 2021-02-07 18:03

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

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

in which that if the two objects

7条回答
  •  醉话见心
    2021-02-07 19:04

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

    #include 
    #include 
    using namespace std;
    
    template
    void func(Type, Type)
    {
        cout << "same" << endl;
    }
    
    template
    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
    

提交回复
热议问题