Can you make a C++ generic function?

前端 未结 7 1451
轮回少年
轮回少年 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:07

    Most probably you need to use templates as other people suggest:

    template 
    return_type func(T const& l, T const& r)
    {
       ...
    }
    

    Because you normally want compilation to fail when the operation implemented by a generic function does not make sense for particular types, so you would either use conditional definition (in the below example is_arithmetic):

    #include 
    #include 
    
    template 
    typename boost::enable_if, return_type>::type
    func(T const& l, T const& r)
    {
        ...
    }
    

    or static assertion in the code to yield the same result:

    #include 
    
    template 
    return_type func(T const& l, T const& r)
    {
        static_assert(boost::is_arithmetic::type::value, "incompatible types");
        ...
    }
    

提交回复
热议问题