有没有办法从函子中取出第一个参数的类型?
Is there a way to pull out the type of the 1st parameter from a functor?
给定任何函子,我想提取它接受的第一个参数的类型。可以假定函子只接受一个参数。我可以用函数做到这一点,但我正在寻找一个函子的解决方案。
#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
现场演示
如果您只想要第一个参数类型,然后你可以使用局部专门化,使用可变模板来分离第一个参数和其余参数。
我的方法和Jeffery一样,但是不使用tuple。
template<typename T>
struct member_fn_traits;
template<typename C, typename R, typename First, typename... Rest>
struct member_fn_traits<R (C::*)(First, Rest...)>
{
using first_type = First;
};
template<typename Functor>
struct fn_traits
{
using first_type = typename member_fn_traits<decltype(&Functor::operator())>::first_type;
};
struct functor
{
void operator()(int*, int) {}
};
auto main()
{
auto first_var = fn_traits<functor>::first_type{};
}
相关文章:
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- 可变参数模板作为第一个参数
- 如何从第一个参数推断第二个参数类型?
- 候选构造函数(隐式复制构造函数)不可行:第一个参数需要 l 值
- 为什么 std::error_code 构造函数的第一个参数固定为 int
- 如何通过 std::apply 调用具有定义的第一个参数的可变参数模板函数?
- 如何获取指向 qsort 第一个参数的向量中第一项的指针?
- 如何在 Lua 回调中检测可选的第一个参数
- 如何让我的 strchr 函数同时将'const char'数组和'char'数组作为第一个参数?
- 在第一个参数上部分专用化模板
- 模板的C 功能将第一个参数设置为第二个参数为默认参数
- 如何获取指向函数第一个参数的指针
- 我可以使用use_lazy_terminal对获得3个参数懒惰的终端的第一个参数
- C++比较运算符重载中第一个参数为 null 时出现分段错误
- Cc 套接字编程 select() 的第一个参数
- 重载运算符:第一个参数对应左操作数,第二个参数对应右操作数
- 仅初始化c++11元组的第一个参数
- 我可以使用成员函数作为EnumWindows的第一个参数吗
- gdb只接受第一个参数
- 等键在 boost::unordered_multimap 中起作用:查询键是否保证是第一个参数