我是新来C++ 11,所以我一直在尝试std::function
今天我试图用它来创建一个字符串的哈希表类函数指针一个小汇编我创造:C++ - 类方法函数指针的unordered_map的初始化列表
assemble.cpp
#include <iostream>
#include <unordered_map>
#include <functional>
#include <vector>
#include <string>
class Assembler {
public:
// Assembles the source file and writes it
bool assemble(std::string output_file);
// Creates the symbol table from a (.s) file
bool create_symbol_table(std::string file_name);
private:
// Hash table for opcode to functions
std::unordered_map<std::string,std::function<bool(std::vector<std::string>)>>
opcode_map =
{
{"add",assemble_data_processing}
};
bool assemble_data_processing(std::vector<std::string> instruction);
};
bool Assembler::assemble_data_processing(std::vector<std::string> instruction) {
std::cout << "Data Processing" << std::endl;
return false;
}
这给我的g ++编译时错误:
g++ -Wall -g -Werror -std=c++11 -o assemble.o assemble.cpp
assemble.cpp:28:5: error: could not convert ‘{{"add", ((Assembler*)this)->Assembler::assemble_data_processing}}’ from ‘<brace-enclosed initializer list>’ to ‘std::unordered_map<std::__cxx11::basic_string<char>, std::function<bool(std::vector<std::__cxx11::basic_string<char> >)> >’ }; ^
但是,如果使功能的非类函数,那么编译没有问题:
bool assemble_data_processing(std::vector<std::string> instruction) {
std::cout << "Data Processing" << std::endl;
return false;
}
我怎样才能在初始化类方法梅开二度初始化器列表unordered_map
?
您是否打算将'assemble_data_processing'设置为静态成员函数? – Frank