If you want to create automatically the functions, use 2pichar's answer with a for loop, but for an emulator you'd probably want something like opcode->int(*)(int)
. This could be done by some tree-like structure:
std::map<char, naive_opcode> opcodes;
struct naive_opcode {
std::map<char, naive_opcode> next;
int(* opcode_func)(int);
};
You'd work through this in some fashion like:
char data;
buf >> data;
naive_opcode opcode = opcodes[data];
while(!opcode.opcode_func){
buf >> data;
opcode = opcode.next[data];
}
opcode.opcode_func(param);
This of course ignores errors and does not include things like the instruction pointer and the .text
section memory, rather replacing it with the buf
buffer for illustrative purposes (In a real life example I'd expect this to be replaced by data=memory[ip]; ++ip;
). This could then be combined with an implementation like:
#include <iostream>
int addone(int x){
return x + 1;
}
int multtwo(int x){
return x * 2;
}
template<int(* F)(int), int(* G)(int)>
int combined(int x){
return F(G(x));
}
int main(){
std::cout << combined<addone,multtwo>(10);
}
for which you could essentially just define the end node of naive_opcode
as {{}, combined<addone,multtwo>}
.
Unfortunately as I mentioned in my comment, this probably cannot be done automatically. The best you could do I recon is that you define something like:
std::vector<std::pair<const char*, int(*)(int)>> raw_opcodes = {{"\x10\x13", addone}, ...};
and then parse that into the tree like structure. As a brief side note: this might not be needed if all the opcodes are 1 byte (which I am unsure about since I am not familiar with NES). Then a simple std::map<char,int(*)(int)> opcodes
will suffice instead of the convoluted naive_opcode
(or better tree) implementation.
Looked it up and it seems that you wouldn't need the tree implementation, but a modification like this can be useful:
template<int(* F)(int)>
int combined(int x){
return F(x);
}
template<int(* F)(int), int(* A)(int), int(*... G)(int)>
int combined(int x){
return F(combined<A, G...>(x));
}
This allows for combining many effects into each other, rather than 2.