2017-08-13 326 views
0

我是新来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

+0

您是否打算将'assemble_data_processing'设置为静态成员函数? – Frank

回答

1

您可以使用std::bind

std::unordered_map<std::string,std::function<bool(std::vector<std::string>)>> 
opcode_map = 
{ 
{"add", std::bind(&Assembler::assemble_data_processing, this, std::placeholders::_1} 
}; 

或λ

std::unordered_map<std::string,std::function<bool(std::vector<std::string>)>> 
opcode_map = 
{ 
{"add", [this](std::vector<std::string> instruction){return assemble_data_processing(instruction);}} 
}; 

或者让你的功能的静态。

0

A std::function不能容纳非绑定成员函数。

根据情况,有三种方法可以解决这个问题。

a)如果assemble_data_processing未使用任何成员数据,请将其设为静态成员函数,并且每天调用它。

b)若您的缓存与单个Assembler实例相关联,然后绑定使用std::bind的功能,采用了类似于:

opcode_map = 
{ 
{"add",std::bind(&Assembler::assemble_data_processing, this, _1)} 
}; 

c)如果Assembler实例是获取以后确定的东西,那么你将不得不抛弃std::function,并使用一个古老的函数指针指向成员函数。

+0

我认为我的原始源代码有点让人误解。我稍后会实例化一个'Assembler'对象。 'assemble_data_processing'指令是专用的,但它没有使用成员函数,所以我猜它可能是一个静态函数。上面12月提出的lambda表达式似乎解决了这个问题。 – Nubcake