【发布时间】: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 " << 5; 将无法工作,因为基类不知道operator<<(int) 或您要添加的任何其他新运算符。
这是一种可接受/标准的方法吗?为什么 STL 不使用 std::ostringstream 做这样的事情?
【问题讨论】:
-
对于工作代码,您可以尝试codereview.stackexchange.com
-
你想摆脱 CRTP 吗?
-
@Jarod42 这叫什么? ???我不明白您的其他评论我明确询问您提到的这个 CRTP,并且没有或很少有帖子。
-
“我显然是在问你提到的这个 CRTP”。不太清楚,因为维克多的回答与此无关。
标签: c++ inheritance operator-overloading crtp