【发布时间】:2022-06-23 00:55:39
【问题描述】:
对于含糊的问题标题,我深表歉意,但我对 C++ 不够熟悉,无法更好地表述它。
我正在尝试创建一个将任何子类上的方法作为参数之一的方法,但我遇到了一个编译器错误,我不知道如何修复。我还想给类型起别名,这样它就不会那么冗长了。我对其他方法持开放态度,但我正在使用的代码或多或少是这样设置的。
代码:
#include <map>
#include <string>
using std::map;
using std::string;
struct ParentClass;
struct DataClass;
using my_handler_type = uint16_t (ParentClass::*)(DataClass&, DataClass&);
struct ParentClass {
void add_handler(string name, my_handler_type handler) {
handlers.emplace(name, handler);
}
private:
map<string, my_handler_type> handlers;
};
struct ChildClass : ParentClass {
private:
uint16_t some_handling_function(DataClass &, DataClass & );
void setup_handler() {
add_handler( "handler_one", &ChildClass::some_handling_function );
}
};
错误:
example.cpp: In member function ‘void ChildClass::setup_handler()’:
example.cpp:31:37: error: cannot convert ‘uint16_t (ChildClass::*)(DataClass&, DataClass&)’ {aka ‘short unsigned int (ChildClass::*)(DataClass&, DataClass&)’} to ‘my_handler_type’ {aka ‘short unsigned int (ParentClass::*)(DataClass&, DataClass&)’}
31 | add_handler( "handler_one", &ChildClass::some_handling_function );
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| |
| uint16_t (ChildClass::*)(DataClass&, DataClass&) {aka short unsigned int (ChildClass::*)(DataClass&, DataClass&) example.cpp:14:51: note: initializing argument 2 of ‘void ParentClass::add_handler(std::string, my_handler_type)’
14 | void add_handler(string name, my_handler_type handler) {
| ~~~~~~~~~~~~~~~~^~~~~~~
【问题讨论】:
-
最好解释一下为什么需要这个,听起来你有 xy 问题。
-
&ChildClass::some_handling_function是short unsigned int (ChildClass::*)(DataClass&, DataClass&),不能隐式转换为short unsigned int (ParentClass::*)(DataClass&, DataClass&)。