gpt4 book ai didi

c++ - 有没有办法从仿函数中提取第一个参数的类型?

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:02 26 4
gpt4 key购买 nike

给定任何仿函数,我想找出它所采用的第一个参数的类型。可以假设仿函数只接受一个参数。我可以用函数来做到这一点,但我正在寻找仿函数的解决方案。

#include <iostream>
#include <utility>

template <typename T>
struct test;

template <typename R, typename P>
struct test<R(*)(P)>
{
typedef R R_t;
typedef P P_t;
};

void fn(int value)
{
std::cout << "function called " << value << std::endl;
}

int main()
{
using namespace std;
cout << typeid(test<decltype(&fn)>::R_t).name() << endl;
cout << typeid(test<decltype(&fn)>::P_t).name() << endl;
}

最佳答案

解决方案

给定:

template <typename T>
struct member_function_traits;

template <typename C, typename R, typename... Args>
struct member_function_traits<R(C::*)(Args...)> {
using return_type = R;

template <std::size_t i>
struct param {
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};

你可以这样做:

template<typename Functor>
struct functor_traits {
using return_type = typename member_function_traits<decltype(&Functor::operator())>::return_type;

template<std::size_t i>
using param = typename member_function_traits<decltype(&Functor::operator())>::template param<i>;
};

例子

例如,有:

struct functor {
void operator()(int) {}
};

以下程序:

std::cout << std::is_same<functor_traits<functor>::return_type, void>::value << std::endl;
std::cout << std::is_same<functor_traits<functor>::param<0>::type, int>::value << std::endl;

将打印:

1
1

Live demo

关于c++ - 有没有办法从仿函数中提取第一个参数的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31946982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com