Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deducing the selected overloaded function type for given argument types

Is it possible to determine the function type of the candidate that overload resolution would select given an overload set and an argument list? For example, given:

char* f(int);
int f(char*);

I would like to be able to write something like:

overload<f, short>::type x;

to declare a variable x of type char* (*)(int).

Is this possible? My first instinct was to write something like this:

template<typename... Args>
struct overload {
    template<typename Ret>
    static auto deduce(Ret (*fptr)(Args...)) -> decltype(fptr);
};

...but this can't handle non-exact matches (i.e. decltype(overload<int>::deduce(f)) works, but decltype(overload<short>::deduce(f)) does not).

like image 584
0x5f3759df Avatar asked Feb 26 '15 02:02

0x5f3759df


1 Answers

C++14 generic lambdas to the rescue:

#define wap_function(f) \
   [](auto&&... args){ return f(std::forward<decltype(args)>(args)...); }

Note that this gem also solves the problem of first-class function templates:

template<typename Lhs, typename Rhs>
auto add(const Lhs& lhs, const Rhs& rhs)
{
    return lhs + rhs;
}

std::accumulate(std::begin(array), std::end(array), 0, wrap_function(add));
like image 141
Manu343726 Avatar answered Nov 15 '22 00:11

Manu343726