Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template for function with N inputs

If it's possible, I would like to define a macro that would take number of arguments in function template ARGS_COUNT and make a template with all argument types being enumerated and output being common type. For example, if it is defined as

TEMPLATE_COMMON_FLOAT(N) /* ...definition...*/

then

TEMPLATE_COMMON_FLOAT(4)
foo(F0 a, F1 b, F2 c, F3 d) { /*...*/ }

should expand to

template <class F0, class F1, class F2, class F3>
  requires std::is_floating_point_v<F0> && std::is_floating_point_v<F1> && std::is_floating_point_v<F2> && std::is_floating_point_v<F3>
std::common_type_t<F0, F1, F2, F3> foo(F0 a, F1 b, F2 c, F3 d) { /*...*/ }

I want this, since I would like to refer to Fi sometimes, instead of bloating function definition with std::floating_point auto and decltypeing after.

like image 572
kusok_kvarka Avatar asked Jun 07 '26 09:06

kusok_kvarka


1 Answers

Using a variadic template should make it possible to have more readable code.

Then, if you want to access the nth argument, you can rely on std::get and the std::tuple machinery

#include <tuple>
#include <iostream>

template <class...Fs>
std::common_type_t<Fs...> foo(Fs&&...fs) {

    // we get the arguments as a tuple.
    auto tup = std::forward_as_tuple(std::forward<Fs>(fs)...);

    // we can access for instance the 4th item (if any)
    static_assert (sizeof...(Fs)>3);
    auto f3 = std::get<3>(tup);

    return f3; // why not ?
}

auto main() -> int
{
    std::cout << foo (0,1,2,3,4) << "\n";
}

Demo

As observed in the comments, you can add a requirement that sets a fixed number of parameters (see here)

If you are mainly interested by retrieving the nth type Fn, you could use some alias that retrieves the required index from a std::tuple defined in the template parameters:

template <class...Fs, typename Ts=std::tuple<Fs...>>
std::common_type_t<Fs...> foo(Fs&&...fs) {
    using F3 = std::tuple_element_t<3,Ts>;
    return {};
}
like image 57
abcdefg Avatar answered Jun 09 '26 01:06

abcdefg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!