在c ++ 11中,如何调用任意可调用对象? [英] In c++ 11, how to invoke an arbitrary callable object?

查看:120
本文介绍了在c ++ 11中,如何调用任意可调用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可调用的概念在 http://en.cppreference.com/w中定义/ cpp / concept / Callable

假设我有一个可调用对象 f ,它的一个参数类型为 T * ,然后返回类型 void f 可以是任何可调用的类型(函数对象,成员函数的指针,数据成员的指针等)。如何调用 f

Suppose I have a callable object f that has one argument of type T* and return type void. f can be any callable type (a function object, a pointer to member function, a pointer to data member, etc). How can I invoke f?

由于f可以是指向成员函数或数据成员的指针,因此仅调用f(x)失败。有没有简单的方法来呼叫 f ?一种可能的解决方案是std :: bind(f,x)(),但是当 f 具有更多参数时,此解决方案会变得更加复杂。

Simply calling f(x) fails since f can be a pointer to member function or data member. Is there a simple way to call f? One possible solution is std::bind(f, x)(), but this solution becomes more complex when f has more arguments.

推荐答案

这正是 std :: invoke 的功能,但是直到C ++ 17才成为标准。您可以制作自己的版本,但是如果要完全通用的话,可能会非常复杂。

This is exactly what std::invoke does, but it won't be standard until C++17. You can make your own version, but it can be pretty complicated if it is fully general.

这是两种情况的基本思想(代码取自cppreference.com):

Here's the basic idea for two cases (code taken from cppreference.com):

template <class F, class... Args>
inline auto INVOKE(F&& f, Args&&... args) ->
    decltype(std::forward<F>(f)(std::forward<Args>(args)...)) {
      return std::forward<F>(f)(std::forward<Args>(args)...);
}

template <class Base, class T, class Derived>
inline auto INVOKE(T Base::*pmd, Derived&& ref) ->
    decltype(std::forward<Derived>(ref).*pmd) {
      return std::forward<Derived>(ref).*pmd;
}

这篇关于在c ++ 11中,如何调用任意可调用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆