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).
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With