less than 1 minute read

Categories:

Tags:

std::invoke was included in c++17 and are inside <functional>.

#include <iostream>
#include <functional>

int do_something(const int i)
{
    return 5+i;
}

struct S
{
    int j=5;
    int do_something(const int i)
    {
        return j+i;
    }

    int do_something_2(const int i)
    {
        return j*i;
    }
};

int main()
{
    //outputs 10
    std::cout << std::invoke(&do_something, 5) << '\n'; 
    
    //outputs 8
    S s;
    std::cout << s.do_something(3) << '\n';

    auto fp = &S::do_something; 
    int (S::*fp2)(int) = nullptr;

    if(true)
    {
        fp2 = &S::do_something_2;
    } else {
        fp2 = &S::do_seomthing
    }
    
    //outputs 7
    std::cout << (s.*fp)(2) <<'\n';
    std::cout << (s.*fp2)(1) <<'\n';



    std::cout << std::invoke(&S::do_something,   s, 10) << '\n';
    std::cout << std::invoke(&S::do_something_2, s, 10) << '\n';

    //we can even use std::invoke to access member data
    std::cout << std::invoke(&S::j, s) << '\n';
}

std::invoke gives universal interface for calling anything thatโ€™s callable. If we do any sort of passing around function pointer, or passing around member pointers, or any kind of templated programming that can take callable things, std::invoke could potentially save lots of efforts in the number of overloads that we need to implement.

Leave a comment