C++ Basics: Call Members Through std::invoke
std::invoke applies a uniform calling interface to ordinary callables, member functions and member data.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as invoke-member-access-demo.cpp:
#include <functional>
#include <iostream>
struct Counter {
int value = 3;
void add(int amount) { value += amount; }
};
int main()
{
Counter counter;
std::invoke(&Counter::add, counter, 4);
std::cout << "after add: " << counter.value << '\n';
int& field = std::invoke(&Counter::value, counter);
field = 10;
std::cout << "after field assignment: " << counter.value << '\n';
const auto doubled = std::invoke([](int value) { return value * 2; }, counter.value);
std::cout << "lambda result: " << doubled << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic invoke-member-access-demo.cpp -o invoke-member-access-demo &&
./invoke-member-access-demoObserved output:
after add: 7
after field assignment: 10
lambda result: 20Read the result
The member function increments the original counter. Invoking the member-data pointer yields a reference, and assigning through that reference changes the same counter. A lambda also fits the interface.
Apply it carefully
For a pointer to member, supply the object before the member-function arguments. Object constness still applies: a non-const member function cannot be called on a const object. Preserve references deliberately; plain auto would copy the member-data result. Any retained reference must not outlive its object.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- invoke-member-access-demo.cpp invoke-member-access-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.