Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an overload address by its parameters only

Assuming that a function (which can be either a global function or a member function) is overloaded only on its parameters (so that its overloads will always be all const or all non-const). Is there a way to write a template that would select an overload address according to the specified parameter? For example:

struct Foo {
    double bar(double n, double m);
    int bar(int n, int m);
};

auto addressDouble = find_overload<&Foo::bar, double, double>::address;
auto addressInt = find_overload<&Foo::bar, int, int>::address;

An interesting answer I've found is here, but unfortunately it only deal with forwarding a call to the right overload, and not actually fetching the overload address so that it can be used later.

Last note: a perfect solution should work on a released Clang version. Apart from this requirement, any available C++1z feature and lower can be used.

like image 443
Maël Nison Avatar asked Nov 08 '22 03:11

Maël Nison


1 Answers

Before you can access to address of an overloaded function you have to specify which version do you need to.

template<typename ...TA>
struct find_overload
{
    template<typename TObj, typename TR>
    using member_func_t = TR(TObj::*)(TA...);

    template< typename TObj, typename TR >
    static constexpr auto get_address(member_func_t<TObj, TR> func) -> member_func_t<TObj, TR>
    {
        return func;
    }
};

int main()
{
    constexpr auto address = find_overload<double, double>::get_address(&Foo::bar);
}
like image 71
MRB Avatar answered Nov 15 '22 07:11

MRB