如何解决在派生类中覆盖运算符重载行为而无需手动重写和单独隐藏每个运算符的标准方法是什么?
https://godbolt.org/z/n9jEK6xsP
#include <iostream>
template <typename Ret = void>
class Base {
public:
using CondRet = typename std::conditional<std::is_same<Ret,void>::value,Base,Ret>::type;
CondRet& operator<<(const char* str) {
std::cout << str;
// downcast,youch.
return *(dynamic_cast<CondRet*>(this));
}
// Pretend there are 10-20 more operator<< overloads here.
virtual ~Base() = default;
};
class Derived : public Base<Derived> {
public:
// bring in all the base operators returning our derived type to this scope.
using Base<Derived>::operator<<;
// Add operator overloads we would like to support in addition to our base operators.
Derived& operator<<(int i) {
std::cout << i;
return *this;
}
~Derived() override = default;
};
int main(int argc,char* argv[]) {
Base<> myBase;
// what have I done?
Derived myDerived;
myDerived << 3 << " four " << 5;
}
否则 " four " << 5;
将无法工作,因为基类将不知道 operator<<(int)
或您想添加的任何其他新运算符。
这是一种可接受的/标准的方法吗?为什么 STL 不使用 std::ostringstream 做这样的事情?
解决方法
我只能建议你在virtual
类中声明Base
运算符,如果Derived
不需要重写,可以省略。创建为 Base
或 Derived
的对象将重用 Base
的运算符。
template <typename Ret>
class Base {
public:
virtual Ret& operator<<(const char* str) { ... }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。