简体   繁体   English

以通用方式分解 C++17 函数式 object?

[英]Decomposing C++17 function-like object in generic fashion?

In C++17 suppose I have a function-like object passed as a parameter to some template:在 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() . 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() .

Is there any way to get the function-like objects arity and type of its parameters and the type of its return type?有什么方法可以获取类似函数的对象的数量及其参数的类型及其返回类型的类型?

I mean, ultimately F could be a class that overloads operator() with multiple different member functions, each with different arities, parameter types and return types - so there isn't a fully-general answer (unless there is some way to iterate that overload set, which I don't think there is).我的意思是,最终 F 可能是一个 class ,它使用多个不同的成员函数重载operator() ,每个成员函数都有不同的参数、参数类型和返回类型 - 所以没有一个完全通用的答案(除非有一些方法可以迭代它重载集,我认为没有)。

But for the typical case where a function call expression involving f results in a single overload, is there a solution?但是对于涉及 f 的 function 调用表达式导致单个重载的典型情况,是否有解决方案?

(also if there is any progress in C++20, worth mentioning too) (如果C++20有什么进展,也值得一提)

C++17's adds deduction guides for std::function , which we can use to do the deduce the function signature of non-overloaded function-like objects: 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)));

If you only wanted the return type, you could just use:如果您只想要返回类型,您可以使用:

using result_type = typename decltype(std::function(f))::result_type;

If you want to avoid std::function altogether because of the compile-time costs, you can implement your own version of the deduction guides for your own type (possibly as general as a function_traits type trait).如果由于编译时成本而想完全避免std::function ,则可以为自己的类型实现自己的演绎指南版本(可能与function_traits类型特征一样通用)。 A sketch of how you might implement the deduction guides yourself can be seen in my answer here: https://stackoverflow.com/a/66038056/1896169在我的回答中可以看到如何自己实施扣除指南的草图: https://stackoverflow.com/a/66038056/1896169

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM