error: ‘invoke’ is not a member of ‘std’

error: ‘invoke’ is not a member of ‘std’

正在使用 g++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609.

我收到错误

slicing.cpp:31:5: error: ‘invoke’ is not a member of ‘std’
slicing.cpp:32:5: error: ‘invoke’ is not a member of ‘std’

编译时

g++ -std=c++17 -O2 -g -Wall -c -o slicing.o slicing.cpp

(与-std=gnu++17相同)代码如下,修改自.

我该如何解决这个问题? 我找不到任何有用的信息。

 #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;
}

使用GCC compiler dialect flag -std=c++1z or even better -std=c++17 and upgrade your compiler to GCC 7.

(ed: 你的编译器看起来有点旧,所以它可能无法工作;注意 GCC 5 was released before the C++17 标准)

使用 g++(x86_64-win32-seh-rev1,由 MinGW-W64 项目构建)7.2.0

它正确构建了这个

#include <iostream>
// C++17
#include <functional>

int Func(int a, int b)
{
  return a + b;
}

struct S
{
  void operator() (int a)
  {
    std::cout << a << '\n';
  }
};


int main(/*int argc, char* argv[]*/)
{
  using namespace std;

  std::cout << std::invoke(Func, 10, 20) << '\n'; // 30
  std::invoke(S(), 42); // 42
  std::invoke([]() { std::cout << "hello\n"; }); // hello

  return 0;
}

来源:https://www.viva64.com/en/b/0533/#ID0EOHKO