gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:43:56 25 4
gpt4 key购买 nike

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

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/

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