为什么 *this
的 derived<T>
类仍然是base<T>
类型?
我以为 typename X
会处理的。
如果这看起来很难看,什么是更好的方法?
失败的尝试:
template <typename T>
class Derived;
template <typename T, typename X>
class Base{
public:
T val;
X f(void){
return *this;
}
};
template <typename T>
class Derived: public Base<T, Derived<T> >{
};
int main(void){
Derived<int> B;
Derived<int> C = B.f();
}
错误:
test4.cpp(9): error: no suitable user-defined conversion from "Base<int, Derived<int>>" to "Derived<int>" exists
return *this;
^
detected during instantiation of "X Base<T, X>::f() [with T=int, X=Derived<int>]" at line 20
compilation aborted for test4.cpp (code 2)
最佳答案
你可以用以下方式来做沮丧:
X f(){ return static_cast<X&>(*this);}
关于c++ - 继承返回 *this 的成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603261/