gpt4 book ai didi

C++ "interfaces"和成员方法中的派生类型参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:19:31 26 4
gpt4 key购买 nike

我正在尝试做这样的事情:

class foo {
virtual void bool operator==(foo const & rhs) = 0;
};

class bar1 : public foo {
bool operator==(bar1 const & rhs) { ... }
};

class bar2 : public foo {
bool operator==(bar2 const & rhs) { ... }
};

也就是说,我想说明的是,所有实现了foo接口(interface)的类都必须为自己的派生类实现operator==方法。

但是,编译器提示 bar1 和 bar2 仍然是抽象类,因为它们还没有实现 operator==(foo const &)

我考虑过在 bar1 和 bar2 中将函数签名更改为 foo const & 然后在函数内部执行 dynamic_cast ,但这看起来很乱:

class bar1 : public foo {
bool operator==(foo const & rhs) {
const bar1 * casted_rhs = dynamic_cast<const bar1 *>(&rhs);
if (casted_rhs == NULL) {
// not a bar1
return false;
} else {
// go through rhs and this object and find out if they're equal
}
}
}

这感觉很乱。

必须有更好的方法来做到这一点。

最佳答案

您可以使用 CRTP模式,以迫使这种情况。通过这种方式,模板基类强制在派生类中实现operator==:

template <typename T>
class foo {
bool operator==(const T & rhs)
{
return static_cast<T>(*this).operator==(static_cast<T>(rhs));
}
};

class bar1 : public foo<bar1> {
bool operator==(const bar1 & rhs)
{
}
};

class bar2 : public foo<bar2> {
bool operator==(const bar2 & rhs)
{

}
};

关于C++ "interfaces"和成员方法中的派生类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8033651/

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