PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to write an overload function for std::array that calls a variadic function?

 November 04, 2022     arrays, c++, lambda, variadic     No comments   

Issue

I have the following variadic function:

template <typename... Args>
CustomType<Args...> method(const Args& args...);

which works fine when I just do e.g.

method(1.0f, 2.0f, 3.0f);

However I also want to write an overload for std::array<T, N>:

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr);

Reading this post I figured I would use the following helper functions:

template <typename T, std::size_t N, typename VariadicFunc, uint32_t... I>
auto methodApply(const std::array<T, N>& arr, VariadicFunc func, std::index_sequence<I...>)
{
    return func(arr[I]...);
}

template <typename T, std::size_t N, typename VariadicFunc, typename Indices = std::make_index_sequence<N>>
auto methodArr(const std::array<T, N>& arr, VariadicFunc func)
{
    return methodApply(arr, func, Indices());
}

and then do

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr)
{
   methodArr(arr, /* what to pass here? */);
}

Note: the reason why I would like to template on func is because I want these helper functions to be generic so that I may use them for other variadic functions, not just method().

Only I'm not sure what pass as the second argument - I was thinking of a lambda function that would make a call to the original function method(const Args& args...) but it's unclear to me how to do this.

EDIT: Restricted to C++14.


Solution

You can wrap it in a lambda and let the compiler deduce the type for you

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr)
{
   return methodArr(arr, [](const auto&... args) { return method(args...); });
}

Demo

In C++17, methodApply can be replaced with std::apply

template <typename T, std::size_t N>
auto method(const std::array<T, N>& arr) {
  return std::apply(
    [](const auto&... args) { return method(args...); }, arr);
}


Answered By - 康桓瑋
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing