Home > Backend Development > C++ > body text

How to Retrieve Argument Types of a Function Pointer in a Variadic Template Class?

Mary-Kate Olsen
Release: 2024-10-31 08:19:30
Original
838 people have browsed it

 How to Retrieve Argument Types of a Function Pointer in a Variadic Template Class?

Retrieving Argument Types of a Function Pointer in a Variadic Template Class

In the previous issue, a generic functor class was created to handle functions with arbitrary argument lists. The issue at hand involves accessing the argument types of the function pointer within the constructor of this class.

To address this issue, you can utilize the function_traits class template:

<code class="cpp">template<typename T>
struct function_traits;

template<typename R, typename ...Args>
struct function_traits<std::function<R(Args...)>>
{
    static const size_t nargs = sizeof...(Args);

    typedef R result_type;

    template <size_t i>
    struct arg
    {
        typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
    };
};</code>
Copy after login

This class provides the following functionality:

  • Extracting the Number of Arguments: The nargs constant represents the count of arguments taken by the function.
  • Establishing the Return Type: The result_type typedef identifies the return type.
  • Determining Individual Argument Types: The arg template struct provides the specific types of each argument.

For example:

<code class="cpp">struct R{};
struct A{};
struct B{};

typedef std::function<R(A,B)> fun;

std::cout << std::is_same<R, function_traits<fun>::result_type>::value << std::endl;
std::cout << std::is_same<A, function_traits<fun>::arg<0>::type>::value << std::endl;
std::cout << std::is_same<B, function_traits<fun>::arg<1>::type>::value << std::endl;</code>
Copy after login

Output:

1
1
1
Copy after login

This example demonstrates how to utilize function_traits to retrieve the argument types within the constructor of a variadic template class.

The above is the detailed content of How to Retrieve Argument Types of a Function Pointer in a Variadic Template Class?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!