[英]CRTP: function with derived-based argument
这是我正在尝试做的最小版本:
template<typename D>
struct Base {
void common() {
// ... do something ...
static_cast<D *>(this)->impl();
// ... do something ...
}
void common_with_arg(typename D::Arg arg) {
// ... do something ...
static_cast<D *>(this)->impl_with_arg(arg);
// ... do something more ...
}
};
struct Derived : Base<Derived> {
void impl() { }
using Arg = int;
void impl_with_arg(Arg arg) { }
};
Base::common()
和Derived::impl()
工作正常(如预期)。 Base::common_with_arg()
和Derived::impl_with_arg()
则不然。
例如,使用 gcc,我收到以下错误:
1.cc: In instantiation of ‘struct Base<Derived>’:
1.cc:18:18: required from here
1.cc:11:7: error: invalid use of incomplete type ‘struct Derived’
void common_with_arg(typename D::Arg arg) {
^~~~~~~~~~~~~~~
1.cc:18:8: note: forward declaration of ‘struct Derived’
struct Derived : Base<Derived> {
直观地(不了解有关模板实例化的所有细节),这似乎是一个明智的错误。 有没有另一种方法可以实现相同的功能?
void common_with_arg(typename D::Arg arg)
// ^^^^^^
您不能在此处访问D::Arg
,因为需要Derived
的定义。 但是定义永远不可用,因为Base
模板正在这里实例化......
struct Derived : Base<Derived> {
// ^^^^^^^^^^^^^
... Derived
尚未完全定义。
一种可能的解决方法是将common_with_arg
函数模板:
template <typename T>
void common_with_arg(T&& arg) {
// ... do something ...
static_cast<D *>(this)->impl_with_arg(std::forward<T>(arg));
// ... do something more ...
}
如果您确实需要Arg
类型别名,请阅读以下问题:
“C++ 静态多态性 (CRTP) 和使用派生类的 typedef” 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.