Example
#include <functional>
constexpr auto sum(auto... ts) { return (ts + ...); }
static_assert(typeid(int) == typeid(std::invoke_r<int>(&sum<short, short>, 3, 4)));
Puzzle
- Can you implement fn
call
which invokes fnsum
with given parametersts...
viainvoke_r
and returns acommon_type
ofts...
sum?
constexpr auto sum(auto... ts) { return (ts + ...); }
[[nodiscard]] constexpr auto call(auto... ts); // TODO
static_assert(6 == call(1, 2, 3));
static_assert(typeid(int) == typeid(call(1, 2, 3)));
static_assert(6u == call(1u, 2u, 3u));
static_assert(typeid(unsigned) == typeid(call(1u, 2u, 3u)));
static_assert(6u == call(1, 2u, 3l));
static_assert(typeid(long) == typeid(call(1, 2u, 3l)));
static_assert(6u == call(1ll, 2ull, 3l));
static_assert(typeid(unsigned long long) == typeid(call(1ll, 2ull, 3l)));
Solutions
[[nodiscard]] constexpr auto call(auto... ts) {
using Ret = std::common_type_t<decltype(ts)...>;
return std::invoke_r<Ret>(sum<decltype(ts)...>, ts...);
}
[[nodiscard]] constexpr auto call(auto... ts){
using T = typename std::common_type_t<decltype(ts)...>;
return std::invoke_r<T>(&sum<decltype(ts)...>, ts...);
}