Advertisements
this is my class:
class Cpu
{
private:
typedef uint8_t(Cpu::*OpCode)();
OpCode *op_codes; // how to define array of 256 function pointers?
uint8_t op_nop();
uint8_t op_lxi();
uint8_t op_stax();
uint8_t op_mov();
uint8_t op_mvi();
...
};
then I would like to initiate the array in class constructor:
Cpu::Cpu()
{
op_codes = new OpCode[256] {
// 0x00
&Intel8080::op_nop,
// 0x01
&Intel8080::op_lxi,
// 0x02:
&Intel8080::op_stax,
// 0x03
...
}
and finally I would like to use the array:
void Cpu::SingleStep()
{
uint8_t op_code = 0x00;
*op_codes[op_code](); // how to execute the specified function?
}
Any help will be appreciate. Thanks!
I tried to define the field in the class using various examples.
OpCode op_codes[256];
but how to assign then functions?
>Solution :
You can use std::invoke
(with C++17) to make a call using member function pointer. Additionally, it would be better to initialize the array in the member initilizer list instead of assigning to it in the constructor body.
//use member initializer list
Cpu::Cpu(): op_codes(new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax})
{
//this is assignment
op_codes = new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax};
}
void Cpu::SingleStep()
{
uint8_t op_code = 0x00;
//call using std::invoke
std::invoke(op_codes[op_code], this);
//old style call without std::invoke
(this->*op_codes[op_code])();
}
can I initialize the array in the ctor body?
We can do assignment inside the ctor body.
Cpu::Cpu()
{
//this is assignment
op_codes = new OpCode[256]{&Cpu::op_nop, &Cpu::op_lxi, &Cpu::op_stax};
}