错误:'invoke'不是'std'的成员

问题描述 投票:0回答:1

使用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相同)代码如下,修改自Virtual functions and std::function?

我怎样才能解决这个问题?我找不到任何有用的信息。

 #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;
}
c++ std
1个回答
2
投票

使用GCC编译器dialect flag -std=c++1z甚至更好的-std=c++17并将您的编译器升级到GCC 7

(编辑:你的编译器似乎有点旧,所以它可能不起作用;请注意GCC 5是在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

© www.soinside.com 2019 - 2024. All rights reserved.