Fundamentals 3 min read

Understanding std::function and std::invoke in C++

This article explains the differences between std::function and std::invoke in C++, shows how std::function can wrap callable objects such as function pointers, and demonstrates using std::invoke to call various callable types—including free functions and member functions—through clear code examples.

IT Services Circle
IT Services Circle
IT Services Circle
Understanding std::function and std::invoke in C++

std::function and std::invoke are distinct components of the C++ standard library with different purposes.

std::function is a type‑erased wrapper that can store any callable object—function pointers, lambdas, functors—allowing them to be invoked later through a uniform call operator.

std::invoke is a function template that provides a generic way to invoke a callable object, handling free functions, member function pointers, and member object pointers uniformly.

Example of using std::function to store a function pointer:

#include <functional>
#include <iostream>

void foo(int a, int b) {
    std::cout << "foo(" << a << ", " << b << ")" << std::endl;
}

int main() {
    std::function<void(int,int)> f = foo;
    f(1, 2);
}

This code wraps the free function foo into a std::function object f and calls it.

Example of using std::invoke to call different callables:

#include <functional>
#include <iostream>

void foo(int a, int b) {
    std::cout << "foo(" << a << ", " << b << ")" << std::endl;
}

class Bar {
public:
    void bar(int a, int b) const {
        std::cout << "Bar::bar(" << a << ", " << b << ")" << std::endl;
    }
};

int main() {
    std::invoke(foo, 1, 2);
    Bar b;
    std::invoke(&Bar::bar, &b, 1, 2);
}

Here std::invoke calls the free function foo and the member function Bar::bar without the caller needing to know the exact callable type.

In summary, use std::function when you need to store and later invoke an arbitrary callable, and use std::invoke when you want a uniform call syntax for various callable types.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CCallabletemplatesstd::functionstd::invoke
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.