什么时候使用 std::invoke 而不是简单地调用可调用对象?

When to use std::invoke instead of simply calling the invokable?

据我了解,std::invoke 允许我执行以下操作:

std::invoke(f, arg1, arg2, ...);

有没有比简单做更有优势的场景:

f(arg1, arg2, ...);

如果可调用对象是指向成员函数的指针,那么您需要执行以下操作之一:

(arg1->*f)(arg2,...);
(arg1.*f)(arg2,...);

取决于 arg1 是什么。

INVOKE(及其对应的官方图书馆 std::invoke)的设计旨在简化此类混乱。

您将使用 std::invoke 来支持代码的调用者传递 any 可调用,而不必使用 lambda 或调用来调整他们的调用站点std::bind.

std::invoke 在创建 lambda 并需要立即调用它时很有用。如果 lambda 很大,后面的括号可能很难观察到:

[] (/* args */) {
    // many lines here
    // ...
} (/* args */)

std::invoke(
    [] (/* args */) {
        // many lines here
        // ...
    },
    /* args */);
#include <iostream>
#include <functional>
template< class Callable, typename ... Args>{}

    //f(args...);   // if arg1 is a class object pointer 
                    // we should use it like this(arg1.*f)(args...); 

    std::invoke(f, args...); //  now  every thing is ok
}

void foo(char c) {
    std::cout << "foo called\n";
}

int main()
{
    struct S {
        int f1(char c) {
            std::cout << "S::f1 called\n";
        }
        void operator()(char c) {
            std::cout << "S::operator() called\n";
        }
    };
    int (S:: * fptr)(char c) = &S::f1;
    S  obj;

    dosomething(fptr, obj, 'a');
    return 0;
}