【问题标题】:What is the standard way to override operator overload behavior in a derived class without manually rewriting and hiding every operator individually?在派生类中覆盖运算符重载行为而不单独手动重写和隐藏每个运算符的标准方法是什么?
【发布时间】:2021-07-23 09:57:55
【问题描述】:

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 " &lt;&lt; 5; 将无法工作,因为基类不知道operator&lt;&lt;(int) 或您要添加的任何其他新运算符。

这是一种可接受/标准的方法吗?为什么 STL 不使用 std::ostringstream 做这样的事情?

【问题讨论】:

  • 对于工作代码,您可以尝试codereview.stackexchange.com
  • 你想摆脱 CRTP 吗?
  • @Jarod42 这叫什么? ???我不明白您的其他评论我明确询问您提到的这个 CRTP,并且没有或很少有帖子。
  • “我显然是在问你提到的这个 CRTP”。不太清楚,因为维克多的回答与此无关。

标签: c++ inheritance operator-overloading crtp


【解决方案1】:

我只能建议你在Base类中声明virtual运算符,如果Derived不需要重写,可以省略。创建为BaseDerived 的对象将重用Base 的运算符。

template <typename Ret>
class Base {
 public:
  virtual Ret& operator<<(const char* str) { ... }
}

【讨论】:

  • 维克多,这不是需要手动重写几十个运算符吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多