c++ - 从转换运算符提取返回和参数类型到函数指针

标签 c++ templates c++11 c++14

是否可以编写一个模板来提取类可转换为的函数指针类型的返回类型和参数类型,而只知道类本身?示例:

struct Foo {
    using FnPtr = int (*)(char, double);

    operator FnPtr() const { ... }
};

// Can I extract the return type (int) and argument types (char and double),
// knowing only `Foo` as an opaque type?

最佳答案

如果 Foo 没有任何其他转换运算符并且没有定义间接运算符,那么您可以依赖 *a_foo 将提供引用到所需类型的函数。从中,您只需提取返回值和参数。

func_ref_traits 这里会进行提取:

template <typename Func>
struct func_ref_traits;

template <typename Ret, typename... Args>
struct func_ref_traits<Ret(&)(Args...)> {
    using ret = Ret;
    using args = std::tuple<Args...>;
};

然后 conv_func_traits 将从给定类型计算出函数类型:

template <typename T>
using conv_func_traits = func_ref_traits<decltype(*std::declval<T>())>;

你可以这样使用它:

conv_func_traits<Foo>::args //std::tuple<char,double>
conv_func_traits<Foo>::ret //int

关于c++ - 从转换运算符提取返回和参数类型到函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38478007/

相关文章:

c++ - 给定的 float 位于哪个段?

c++ - 欧拉的巨数披

c++ - 如何将 unsigned long 转换为 64 位的 time_t

c++ - 无法使用 std::function 作为参数类型(需要函数指针版本)宁愿像 STL 这样的模板,但它不能推导参数

c++ - std::hash 和/或 boost::hash 的目的是什么?

c++ - 在函数退出前调用函数

c++ - 如果将 "+m"用作输出约束,gcc 能否正常工作?

c++ - 模板化父类(super class)链接问题

c++ - 检查运算符是否在 C++ 中重载

c++ - 如何在不使用时间作为种子的情况下在 C++ 中生成随机数