gpt4 book ai didi

c++ - 将指针从派生类方法转换为基类

转载 作者:行者123 更新时间:2023-11-30 00:48:18 24 4
gpt4 key购买 nike

假设我想创建一个层次结构来响应以字符串编码的特定事件。例如来自网络的命令。想法是有一个 Base 类处理网络连接,接收缓冲区,拆分它等,命令 react 的处理在派生类中(派生类也可以添加一些新词来处理)。所以我的解决方案是:

class Base {
public:
typedef void (Base::*Method)();
typedef std::unordered_map<std::string, Method> Methods;

void reactToA();
void reactToB();

Base() :
methods{
{ "A", &Base::reactToA },
{ "B", &Base::reactToB }
}
{
}
void action( const std::string &s )
{
auto f = methods.find( s );
if( f != methods.end() )
(*this.*)(f->second)();
}

protected:
Methods methods;
};

class Child : public Base {
public:
void reactToB();
void reactToC();

Child() {
methods[ "B" ] = static_cast<Method>( &Child::reactToB );
methods[ "C" ] = static_cast<Method>( &Child::reactToC );
}
};

所以我必须将指向 Child 方法的指针转换为指向 Base 方法的指针。类型转换定义明确吗?是否有更优雅(或正确,如果这导致 UB)解决方案?

最佳答案

来自 [expr.static.cast]:

A prvalue of type “pointer to member of D of type cv1 T” can be converted to a prvalue of type “pointer to member of B” of type cv2 T, where B is a base class (Clause 10) of D, if a valid standard conversion from “pointer to member of B of type T” to “pointer to member of D of type T” exists (4.11), and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. [...] If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the behavior is undefined.

在我们的例子中,&Base::reactToB可以转换为&Child::reactToB , 但自 Base 包含原始成员,则行为未定义。

您必须存储类似 std::function<void(Base*)> 的内容或 void(*)(Base*) .

如果是前者,您可以向Base 添加一个成员函数。喜欢:

template <typename C>
void addMethod(std::string const& name, void (C::*method)()) {
methods[name] = [method](Base* b){
(static_cast<C*>(b)->*method)();
};
}

addMethod("B", &Child::reactToB);

如果是后者,你可以这样做:

methods[ "B" ] = +[](Base* b){ 
static_cast<Child*>(b)->reactToB();
};

关于c++ - 将指针从派生类方法转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32013915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com