Can you make a C++ generic function?

前端 未结 7 1294
轮回少年
轮回少年 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 <class T>
    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 <boost/utility/enable_if.hpp>
    #include <boost/type_traits/is_arithmetic.hpp>
    
    template <class T>
    typename boost::enable_if<boost::is_arithmetic<T>, return_type>::type
    func(T const& l, T const& r)
    {
        ...
    }
    

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

    #include <boost/type_traits/is_arithmetic.hpp>
    
    template <class T>
    return_type func(T const& l, T const& r)
    {
        static_assert(boost::is_arithmetic<T>::type::value, "incompatible types");
        ...
    }
    
    0 讨论(0)
提交回复
热议问题