Skip to content

Latest commit

 

History

History
62 lines (41 loc) · 1.61 KB

334.md

File metadata and controls

62 lines (41 loc) · 1.61 KB
Info

Example

#include <functional>

constexpr auto sum(auto... ts) { return (ts + ...); }
static_assert(typeid(int) == typeid(std::invoke_r<int>(&sum<short, short>, 3, 4)));

https://godbolt.org/z/1Wd6Ms3Wa

Puzzle

  • Can you implement fn call which invokes fn sum with given parameters ts... via invoke_r and returns a common_type of ts... 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)));

https://godbolt.org/z/3WP5YG8dv

Solutions

[[nodiscard]] constexpr auto call(auto... ts) {
    using Ret = std::common_type_t<decltype(ts)...>;
    return std::invoke_r<Ret>(sum<decltype(ts)...>, ts...);
}

https://godbolt.org/z/1baMcc331

[[nodiscard]] constexpr auto call(auto... ts){
    using T = typename std::common_type_t<decltype(ts)...>;
    return std::invoke_r<T>(&sum<decltype(ts)...>, ts...);
}

https://godbolt.org/z/xcn9qnrcY