Joh*_*han 2 c++ templates fluent-interface crtp chaining
有没有办法从子类链接调用超类而不强制转换,重写方法或使用接口.比如做的时候
class A {
public:
A& foo() { return *this; }
};
class B : public A {
public:
B& bar() { return *this; }
};
int main(void) {
B b;
b.foo().bar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用clang编译时我得到了错误
main.cpp:13:10: error: no member named 'bar' in 'A'
b.foo().bar();
~~~~~~~ ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么(因为A返回对self的引用),但我希望它返回它的子类B类,因为它在该上下文中被调用.这可能吗?或者我需要将B定义为
class B : public A {
public:
B& bar() { return *this; }
B& foo() { A::foo(); return *this; }
};
Run Code Online (Sandbox Code Playgroud)
并使foo()虚拟?
您可以使用CRTP模式:
template<class Derived>
class A {
public:
Derived& foo() { return *static_cast<Derived*>(this); }
};
class B : public A<B> {
public:
B& bar() { return *this; }
};
int main(void) {
B b;
b.foo().bar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)