c++ - 获取函数参数类型作为元组

标签 c++ templates c++17 variadic-templates template-argument-deduction

问题

Given any function (or callable) type Function, how can I get its all arguments types as a tuple type ?

例如,我需要一个特征 function_traits<Function>::arguments ,其中:

int f();
typename function_traits<decltype(f)>::arguments // => gives me std::tuple<>

void g(int);
typename function_traits<decltype(g)>::arguments // => gives me std::tuple<int>

void h(int, int);
typename function_traits<decltype(h)>::arguments // => gives me std::tuple<int, int>

我的想法

首先

我需要获取参数的大小,幸好 boost 已经实现了 function_traits<F>::arity

然后

生成 std::integer_sequence从 1 到 artify,将其映射到参数类型,但问题来了,映射 integer_sequence ,我需要这样的东西:

function_traits<F>::arg_type<N> // -> N-th arg_type

但 boost 只提供了这个:

function_traits<F>::argN_type

问题

我如何实现 function_traits<F>::arg_type<N> ?我可以使用最高为 c++17 的 c++ 标准

最佳答案

像这样:

#include <tuple>

template<typename x_Function> class
function_traits;

// specialization for functions
template<typename x_Result, typename... x_Args> class
function_traits<x_Result (x_Args...)>
{
    public: using arguments = ::std::tuple<x_Args...>;
};

使用示例:

#include <type_traits>

int foo(int);

using foo_arguments = function_traits<decltype(foo)>::arguments;
static_assert(1 == ::std::tuple_size<foo_arguments>::value);
static_assert(::std::is_same_v<int, ::std::tuple_element<0, foo_arguments>::type>);

online compiler

关于c++ - 获取函数参数类型作为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622162/

相关文章:

c++ - 如何在 Cv::Mat 图像中放置一些文本(变量)

c++ - 如何在C++中有条件地编写依赖于lambda返回类型的代码?

c++ - 为什么 std::find_if(first, last, p) 不通过引用获取谓词?

c++ - 用户提供的 std::allocator 特化

c++ - 非类型模板参数、构造函数和推导指南

c++ - 在 C++ 中使用 regex/boost 查找两个数字之间的数字

c++ - 小单元测试

c++ - 为什么我的 Stack 实现中的第 98 个元素的值如此奇怪?

c++ - 如何拥有任意类型的模板参数?

c++ - 在默认参数中使用依赖范围作为 std::less 类型的编译错误