访问不完整类型的成员类型

Accessing a member type of an incomplete type

编译它的解决方法是什么?

#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 函数可以通用地用于许多不同的 classes.

我很确定您不能在 'using' 情况下使用 CRTP。您可以将它用于方法和成员,但不能用于类型之类的东西。但是,在使用模板时,将类型作为模板参数非常有用,所以为什么不这样做呢

template <typename Derived, typename Type>
....

哪个会工作得很好。

一个有点疯狂的选择是推迟评估,直到尝试调用 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 是微不足道的