使用结构映射之前无效的声明符?

Fun*_*uit 1 c++ struct

我正在尝试映射strings 和自定义结构之间的映射,callable. 但是,它给了我“无效的声明者”。我已经尝试了很多东西,比如typedefing it (eg typdef struct _c { } callable;) 但这只会引发更多错误。

我正在使用 ideone.com 进行编译,因为我在学校没有编译器,但我仍然想至少敲出体面的代码。

一个最小的例子(ideone 链接):

#include <vector>
#include <map>
#include <iostream>
#include <string>
using namespace std;

struct callable {
  virtual void operator()(vector<string> args) = 0;
}

std::map<std::string, callable> commands =
{
  { "cmd", struct : callable
    {
      operator()(vector<string> args) {
        out << "cmd called with args:" << endl;
        for (auto i = args.begin(); args.end() != i; ++i) out << *i << endl;
      }
    }
  }
}

int main() {
  vector<string> args = {"hello", "world"};
  commands["cd"](args);
}
Run Code Online (Sandbox Code Playgroud)

错误是:

#include <vector>
#include <map>
#include <iostream>
#include <string>
using namespace std;

struct callable {
  virtual void operator()(vector<string> args) = 0;
}

std::map<std::string, callable> commands =
{
  { "cmd", struct : callable
    {
      operator()(vector<string> args) {
        out << "cmd called with args:" << endl;
        for (auto i = args.begin(); args.end() != i; ++i) out << *i << endl;
      }
    }
  }
}

int main() {
  vector<string> args = {"hello", "world"};
  commands["cd"](args);
}
Run Code Online (Sandbox Code Playgroud)

预期输出:

prog.cpp:11:33: error: invalid declarator before 'commands'
 std::map<std::string, callable> commands =
                                 ^
Run Code Online (Sandbox Code Playgroud)

作为旁注,请在回答将字符串映射到代码的更一般性问题之前提供此问题的答案,除非此方法不起作用。

Mic*_*rus 9

您忘记了结构后的额外分号:

struct callable {
  virtual void operator()(vector<string> args) = 0;
}; // <--- ; is needed.
Run Code Online (Sandbox Code Playgroud)

这就是给你编译器错误的原因。