Can you make a C++ generic function?

前端 未结 7 1296
轮回少年
轮回少年 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 18:54

    OP seems to want to know if the 2 objects are comparable or not. You can use template specialization to achieve this (note: this doesn't compile on VC 10, but does on g++ 4.7). The only nuance, is you want this function to

    they are compared and a comparison value is returned otherwise some other value is returned to indicate a comparison was not possible

    But you need to define some sort of structure to signify that a comparison was not possible; using a magic number '-500' or whatever is not good style. Alternately, you could throw an error, and allow it to be caught an handled.

    struct NoCompare{};
    
    template 
    static auto compare2(const U1 & u1, const U2 & u2) -> decltype(u1 == u2)
    { 
        cout << "Comparable" << endl;
        return u1 == u2;
    }
    
    static int compare2(...) 
    { 
        // Comparison not supported - return whatever value you want. (change the return type as appropriate)
        cout << "Not comparable" << endl;
        return -500;
    }
    
    int main()
    {
        int a = 5, b = 3, c = 3;
        NoCompare dns;
        cout << compare2(a, b) << endl;
        cout << compare2(dns, b) << endl;
        cout << compare2(c, b) << endl;
    
        return 0;
    }
    

    Output: C:\MinGW\MinGW>a Comparable 0 Not comparable -500 Comparable 1

提交回复
热议问题