Skip to content

Latest commit

 

History

History
77 lines (57 loc) · 2.01 KB

variadic_function.md

File metadata and controls

77 lines (57 loc) · 2.01 KB

Meta type variadic function (tkVariadicFunction)

Template metapp::VariadicFunction is used to create a variadic function.

template <typename FT>
struct VariadicFunction
{
  explicit VariadicFunction(const Variant & func);
};

FT is the function prototype.
The parameter func in the constructor is a callable Variant that implements MetaCallable interface. It can be constructor, function pointer, member function pointer, etc.
The callable must have the prototype as,

ResultType callable(const metapp::ArgumentSpan & arguments)

The function can have any result type.
Parameter arguments is an ArgumentSpan object. It's used to pass the arguments.
For more details on ArgumentSpan, please see document for MetaCallable

The arguments are passed from lef to right order.

VariadicFunction is an adaptor to dedicate any invoking to func, and convert the arguments to the arguments array.

To deduce FT, we can use the non-member function to create createVariadicFunction,

template <typename FT>
VariadicFunction<FT> createVariadicFunction(FT && func);

Now let's see how to use VariadicFunction.

Assume we have this function

int sum(const metapp::ArgumentSpan & arguments)
{
  int total = 0;
  for(const auto & argument : arguments) {
    total += argument.cast<int>().get<int>();
  }
  return total;
}

Create the VariadicFunction Variant

metapp::Variant func = (metapp::createVariadicFunction(&sum));

Invoke func without arguments

ASSERT(metapp::callableInvoke(func, nullptr).get<int>() == 0);

Invoke func with 2 arguments

ASSERT(metapp::callableInvoke(func, nullptr, 6, 3).get<int>() == 9);

Invoke the function with 10 arguments, the arguments can have different type, as long as the target function can process (cast) them.

ASSERT(metapp::callableInvoke(func, nullptr,
  10, 9.1, 8LL, 7, 6, 5, 4, 3, 2, 1).get<int>() == 55);