c++ - 访问不完整类型的成员类型

标签 c++ templates crtp

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

#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/

相关文章:

c++ - 如何使函数永久更改全局数组

c++ - C++ 中的模板类……必需的技能集?

c++ - 从共享库公开 C++ 模板方法

C++ operator<< gtest AssertionFailure 编译错误

c++ - CRTP 和默认赋值运算符

c++ - Boost 库和应用程序中不同的 C++ 损坏名称

c++ - 如何在C++中删除新数组?

c++ - 是否有 boost::weak_intrusive_pointer?

c++ - 是否可以从较晚的模板参数推断或默认较早的模板参数?

c++ - libclang 可以解析 CRTP 模式吗?