c++ - 从多个函数指针中提取参数参数列表的元函数

标签 c++ function types parameters metaprogramming

对于单个函数,可以像这样提取其参数类型:

template <class T>
struct Foo;

template <class Ret, class... Args>
struct Foo<Ret(*)(Args...)> { /* stuff */ };

是否可以对一系列函数指针做同样的事情?那是, 能够提取参数然后以相同的方式重新部署它们?例如。像这样的东西:

template <class.. T>
struct Foo;

template <class... Rets, class... Args>
struct Foo<Rets(*)(Args...)...>           // I wish this worked
{
    std::tuple<Rets(*)(Args...)...> fns;  // Ditto
}

最佳答案

派对迟到了,但这可能会有用。首先让我们定义一些实用程序:

template <class... T>
using void_t = void;

template <bool...> struct bool_pack;

template <bool... v>
using all_true = std::is_same<bool_pack<true, v...>, bool_pack<v..., true>>;

然后是一个元函数来检查一个类型是否是一个函数指针:

template <class F>
struct is_function_pointer : std::integral_constant<bool, false> { };

template <class Ret, class... Args>
struct is_function_pointer<Ret (*)(Args...)> : std::integral_constant<bool, true> { };

使用这些,让我们编写类。 SFINAE 开关放在第一位,因为可变参数包占据了右侧:

template <class = void_t<>, class... T>
struct Foo_impl;

template <class... FuncPtrs>
struct Foo_impl<
    std::enable_if_t<all_true<is_function_pointer<FuncPtrs>{}...>{}>,
    FuncPtrs...
> {
    std::tuple<FuncPtrs...> fns;
};

最后,对用户隐藏 SFINAE 开关的 typedef:

template <class... T>
using Foo = Foo_impl<void_t<>, T...>;

瞧! Foo<void (*)(), int (*)(double)>去特化Foo_impl其中包含足够的元组,Foo<int, double>转到主模板。

See it live on Coliru

关于c++ - 从多个函数指针中提取参数参数列表的元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38975991/

相关文章:

c++ - 返回具有不同模板参数值的不同类型(但类型相同)

c++ - 使用 Eclipse 检查 GCC 版本

javascript - 为所有目标元素调用 javascript 函数

scala - Scala 中 zipAll 实现中奇怪的类型不匹配

java - 允许 Scala/Java 中的参数化类/类型

c++ - 在数据结构中存储不同尺寸的图像,OpenCV

python - 允许程序取最接近时间的值的函数

Php函数展开化学方程式

具有模板成员变量的 C++ 类

c++ - Netbeans Cpp 编译并运行项目,但不使用 cppunit 进行测试