Using g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609.
I receive the error
slicing.cpp:31:5: error: ‘invoke’ is not a member of ‘std’
slicing.cpp:32:5: error: ‘invoke’ is not a member of ‘std’
When compiling with
g++ -std=c++17 -O2 -g -Wall -c -o slicing.o slicing.cpp
(and the same with -std=gnu++17
) code below, modified from Virtual functions and std::function?.
How can I fix this? I could not find any useful information.
#include <functional>
#include <iostream>
struct base
{
base() {std::cout << "base::base" << std::endl;}
virtual ~base() {std::cout << "base::~base" << std::endl;}
virtual void operator()() {std::cout << "base::operator()" << std::endl;}
};
struct derived1: base
{
derived1() {std::cout << "derived1::derived1" << std::endl;}
virtual ~derived1() {std::cout << "derived1::~derived1" << std::endl;}
virtual void operator()() {std::cout << "derived1::operator()" << std::endl;}
};
struct derived2: base
{
derived2() {std::cout << "derived2::derived2" << std::endl;}
virtual ~derived2() {std::cout << "derived2::~derived2" << std::endl;}
virtual void operator()() {std::cout << "derived2::operator()" << std::endl;}
};
int main(int argc, char* argv[])
{
base* ptr1 = new derived1();
base* ptr2 = new derived2();
std::function<void()> f1 = *ptr1;
std::function<void()> f2(*ptr2);
std::invoke(*ptr1); // calls derived1::operator()
std::invoke(*ptr2); // calls derived2::operator()
//std::invoke(f1); // calls base::operator()
//std::invoke(f2); // calls base::operator()
delete ptr1;
delete ptr2;
return 0;
}