在 C++ 中将匿名函数分配给函数指针方法
Assigning anonymous functions to function-pointer methods in C++
我正在尝试创建一个简单的 CPU 模拟器。
CPU
class 有一个 hash_map<uint8_t, Instruction> instructionTable;
并且在 CPU
构造函数中我想创建所有 Instruction
对象并将它们插入 instructionTable
.
Instruction.h:
#ifndef INSTRUCTION_H
#define INSTRUCTION_H
#include <cstdint>
#include <string>
#include "CPU.h"
class Instruction
{
public:
uint8_t opcode;
Instruction();
void(*execute)(CPU* cpu);
};
#endif
CPU.h:
#ifndef CPU_H
#define CPU_H
#include <cstdint>
#include <unordered_map>
#include "Instruction.h"
#include "Memory.h"
class CPU
{
public:
Memory* memory;
CPU(Memory* memory);
void loadInstructionSet();
};
#endif
CPU.cpp:
#include "stdafx.h"
#include "CPU.h"
#include <string>
#include <iostream>
CPU::CPU(Memory* memory){
this->memory = memory;
}
void CPU::loadInstructionSet(){
Instruction *LDA = new Instruction();
LDA->execute = [](CPU*) { std::cout << "execute LDA..."; };
}
我现在如何创建 Instruction
对象并分配新的执行函数?
我认为 lambda 表达式/匿名函数用于此类事情。
LDA->execute = { cout << "execute LDA..."; }();
这应该是
LDA->execute = [](CPU*) { cout << "execute LDA..."; };
首先,在行末尾的方括号中,您实际上是在创建 lambda 后立即调用它。
其次,execute
的类型定义表明该函数需要指向 CPU
的指针,但在 lambda 中,您通过值而不是指针获取 CPU
。
这一行:
void *(execute)(CPU* cpu);
是一个函数声明。要声明 函数指针 ,请使用
void (*execute)(CPU* cpu);
Cannot convert from void
to void (__cdecl *)(void)
这是因为您调用了 lambda,而它的 return 表达式不存在,即等于 void。删除最后一个括号:
LDA->execute = []() { cout << "execute LDA..."; };
另请注意 a lambda can only be converted to a function pointer if it does not capture。
更喜欢使用 std::function
而不是原始函数指针。
我正在尝试创建一个简单的 CPU 模拟器。
CPU
class 有一个 hash_map<uint8_t, Instruction> instructionTable;
并且在 CPU
构造函数中我想创建所有 Instruction
对象并将它们插入 instructionTable
.
Instruction.h:
#ifndef INSTRUCTION_H
#define INSTRUCTION_H
#include <cstdint>
#include <string>
#include "CPU.h"
class Instruction
{
public:
uint8_t opcode;
Instruction();
void(*execute)(CPU* cpu);
};
#endif
CPU.h:
#ifndef CPU_H
#define CPU_H
#include <cstdint>
#include <unordered_map>
#include "Instruction.h"
#include "Memory.h"
class CPU
{
public:
Memory* memory;
CPU(Memory* memory);
void loadInstructionSet();
};
#endif
CPU.cpp:
#include "stdafx.h"
#include "CPU.h"
#include <string>
#include <iostream>
CPU::CPU(Memory* memory){
this->memory = memory;
}
void CPU::loadInstructionSet(){
Instruction *LDA = new Instruction();
LDA->execute = [](CPU*) { std::cout << "execute LDA..."; };
}
我现在如何创建 Instruction
对象并分配新的执行函数?
我认为 lambda 表达式/匿名函数用于此类事情。
LDA->execute = { cout << "execute LDA..."; }();
这应该是
LDA->execute = [](CPU*) { cout << "execute LDA..."; };
首先,在行末尾的方括号中,您实际上是在创建 lambda 后立即调用它。
其次,execute
的类型定义表明该函数需要指向 CPU
的指针,但在 lambda 中,您通过值而不是指针获取 CPU
。
这一行:
void *(execute)(CPU* cpu);
是一个函数声明。要声明 函数指针 ,请使用
void (*execute)(CPU* cpu);
Cannot convert from
void
tovoid (__cdecl *)(void)
这是因为您调用了 lambda,而它的 return 表达式不存在,即等于 void。删除最后一个括号:
LDA->execute = []() { cout << "execute LDA..."; };
另请注意 a lambda can only be converted to a function pointer if it does not capture。
更喜欢使用
std::function
而不是原始函数指针。