Home  >  Article  >  Backend Development  >  How to Retrieve Argument Types of Function Pointers in Variadic Template Classes?

How to Retrieve Argument Types of Function Pointers in Variadic Template Classes?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 02:49:01466browse

How to Retrieve Argument Types of Function Pointers in Variadic Template Classes?

Retrieving Argument Types of Function Pointers in Variadic Template Classes

Generic functors are useful classes that provide a convenient way to handle functions with varying argument lists. However, accessing the argument types of function pointers within these classes can be a challenge.

Solution

Consider the following functor class:

<code class="cpp">template <typename... ARGS>
class Foo {
    std::function<void(ARGS...)> m_f;
public:
    Foo(std::function<void(ARGS...)> f) : m_f(f) {}
    void operator()(ARGS... args) const { m_f(args...); }
};</code>

While you can easily access the args... in the operator() method using a recursive "peeling" function, obtaining the argument types in the constructor is more complex.

To address this, you can implement a function_traits class:

<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>

With this class, you can determine the argument types, return type, and number of arguments of a function pointer.

Test Code

The following code demonstrates the functionality:

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

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

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

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

Statement:
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