[英]Decomposing C++17 function-like object in generic fashion?
在 C++17 假设我有一个类似函数的 object 作为参数传递给某个模板:
template<typename F>
void g(F f) {
auto x = f(/*...*/);
}
There are lots of different types F could be, such as a function pointer, a std::function, a lambda expression, and in fact any class type that implements operator()
.
有什么方法可以获取类似函数的对象的数量及其参数的类型及其返回类型的类型?
我的意思是,最终 F 可能是一个 class ,它使用多个不同的成员函数重载operator()
,每个成员函数都有不同的参数、参数类型和返回类型 - 所以没有一个完全通用的答案(除非有一些方法可以迭代它重载集,我认为没有)。
但是对于涉及 f 的 function 调用表达式导致单个重载的典型情况,是否有解决方案?
(如果C++20有什么进展,也值得一提)
C++17 为std::function
添加了推导指南,我们可以使用它来推导非重载类函数对象的 function 签名:
template <typename R, typename... Args>
constexpr auto do_something_with_the_signature(std::function<R(Args...)>) {
// Assuming that you only care about the return type.
// Otherwise, you may want some kind of wrapper to extract the signature to
// avoid runtime cost
}
...
using some_type_computation =
decltype(do_something_with_the_signature(std::function(f)));
如果您只想要返回类型,您可以使用:
using result_type = typename decltype(std::function(f))::result_type;
如果由于编译时成本而想完全避免std::function
,则可以为自己的类型实现自己的演绎指南版本(可能与function_traits
类型特征一样通用)。 在我的回答中可以看到如何自己实施扣除指南的草图: https://stackoverflow.com/a/66038056/1896169
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.