编译它的解决方法是什么?
#include <iostream>
template <typename Derived>
struct CRTP {
void foo (const typename Derived::type& a) {std::cout << a << '\n';}
};
struct A : CRTP<A> {
using type = int;
};
struct B : CRTP<B> {
using type = std::string;
};
// etc...
int main() {
A a;
a.foo(5);
}
这不会编译,因为在 CRTP<A>
的实例化时, A
还不是一个完整的类(class),所以 A::type
无法访问。但是解决方法是什么?我需要这种类型的设计,以便 foo 函数可以通用地用于许多不同的类。
最佳答案
一个有点疯狂的选择是推迟评估,直到尝试调用 foo
,此时 Derived
将完成。这需要将其设为模板。
template <typename Derived>
struct CRTP {
template<class T = Derived>
void foo (const typename T::type& a) {std::cout << a << '\n';}
};
如果需要,可以通过 static_assert
阻止使用非 Derived
的类型调用 foo
。
关于c++ - 访问不完整类型的成员类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35908296/