简体   繁体   English

通过指针调用静态成员函数

[英]Call static member function by pointer

I'm working on a small custom Assembler 我正在开发一个小型的定制汇编程序

I have a vector of struc to storing OPCODE informations (Mnemonic, number and type of argument, parsing function,...) 我有一个struc来存储OPCODE信息(助记符,参数的数量和类型,解析函数等)。

typedef char    args_type_t;

typedef struct  op_s {
    std::string     opcode;
    char            nbr_args;
    args_type_t     type[4];
    int             code;
    Tryte           (*fct)(std::vector<std::string>);
} op_t;

the parsing function is pointer on a static member function : 解析函数是静态成员函数上的指针:

{"MOV", 2, {T_REGISTER | T_ADDRESS, T_REGISTER | T_ADDRESS | T_CONSTANT}, 1, &Opcodes::MOV},

and the function : 和功能:

class Opcodes
{
public:
    static Tryte Opcodes::MOV(std::vector<std::string> _opMap) {
        return Tryte(0);
    }
};

I try this, but I get SEGFAULT ( str() is a member function of Tryte) : 我尝试了这个,但是得到了SEGFAULT( str()是Tryte的成员函数):

for (int i = 0; i < opMap.size(); i++) {
    for (int j = 0; j < op_tab.size(); j++) {
        if (!op_tab[j].opcode.compare(opMap[i][2])) {
            std::cout << "OPBYTE : " << op_tab[j].fct(opMap[i]).str() << std::endl;
        }
    }
}

I want to call my function without instanciate Opcodes object it's posible ? 我想在没有可能的Opcodes对象的情况下调用我的函数吗?

EDIT : 编辑:

my error was here : if (!op_tab[j].opcode.compare(opMap[i][2])) my mnemonic is the 1st item n opMap 我的错误在这里: if (!op_tab[j].opcode.compare(opMap[i][2]))我的助记符是opMap的第一项

Your code seems right, so perhaps a debugger information could help a bit. 您的代码似乎正确,因此调试器信息可能会有所帮助。 But we can try to improve the friendlyness of the code by using a std::function: 但是我们可以尝试使用std :: function来提高代码的友好性:

typedef char    args_type_t;

#include <functional>
typedef struct  op_s {
    std::string     opcode;
    char            nbr_args;
    args_type_t     type[4];
    int             code;
    std::function<Tryte(std::vector<std::string>>)>  fct;
} op_t;

As for the sefgault, send us the backtrace. 至于后悔,请给我们回溯。 Also, try to use range-based-for as it doesn't needs to tranverse the map to get the element again (as you are doing inside of the inner loop) 另外,请尝试使用基于范围的for,因为它不需要遍历地图即可再次获取元素(就像您在内部循环中所做的一样)

for (auto op : opMap) {
    for (auto tab : op_tab) {
        if (!tab.opcode.compare(op[1])) {
            std::cout << "OPBYTE : " << tab.fct(op).str() << std::endl;
        }
    }
}

One common fix that you can do to not miss the indexes anymore is to use an Enum holding the possibilities. 您可以再做一次不丢失索引的常见解决方法是使用Enum来保持可能性。

enum Columns {
    FuncPointer,
    UserData
}

for (auto op : opMap) {
    for (auto tab : op_tab) {
        if (!tab.opcode.compare(op[FuncPointer])) {
            std::cout << "OPBYTE : " << tab.fct(op).str() << std::endl;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM