C++ 泛型编程 CRTP 基类继承自派生类型提供的类

标签 c++ templates crtp

阅读 Stroustrup 的“The C++ Programming Language”,第 4 版。 27.4.1 Composing Data Structures 中有一些我无法理解的示例代码。使用派生类(CRTP 模式)通过模板参数提供的基类中的类型别名时会出现问题。

 1 #include <vector>
 2 using namespace std;
 3 struct Red_black_balance {};
 4 template<typename N>
 5 struct Node_base : N::balance_type { //<==
 6     N* left_child;
 7     N* right_child;
 8     Node_base() { }
 9 };
10 template<typename Val, typename Balance>
11 struct Search_node : Node_base<Search_node<Val, Balance>>
12 {
13    using balance_type = Balance; // <==
14    Val val;
15    Search_node(Val v): val(v) {}
16 };
17 template<typename T>
18 using Rb_node = Search_node<T, Red_black_balance>; 
19 using My_node = Rb_node<double>;
20 int main(int, char **)
21 {
22    My_node my_root(0.0);
23    return 0;
24 }

这是编译器输出(g++ 版本 4.9.2):

$ g++ -std=c++11 -Wall -pedantic -o test15 test15.cpp
test15.cpp: In instantiation of ‘struct Node_base<Search_node<double, Red_black_balance> >’:
test15.cpp:11:8:   required from ‘struct Search_node<double, Red_black_balance>’
test15.cpp:22:17:   required from here
test15.cpp:5:8: error: no type named ‘balance_type’ in ‘struct Search_node<double, Red_black_balance>’
 struct Node_base : N::balance_type {
        ^

据我了解,当在 main() 中完成模板实例化时,所有模板依赖类型都应根据此时的信息生成(与在模板定义时实例化的非依赖类型不同) .所以编译器在main中生成Node_base实例的时候应该知道N::balance_type对应的是什么吧?但它似乎没有。知道代码中有什么问题吗?

最佳答案

这实际上是一个循环依赖问题。

template<typename N>
struct Node_base : N::balance_type

为了实例化Node_base<N> ,我们需要先看N::balance_type .

template<typename Val, typename Balance>
struct Search_node : Node_base<Search_node<Val, Balance>>

为了实例化Search_node<Val, Balance> ,我们需要先实例化Node_base<Search_node<Val, Balance>> .这需要实例化 Search_node<Val, Balance>::balance_type ,这需要实例化 Search_node<Val, Balance> .

你可以通过 Balance分别在:

template <typename Derived, typename Balance>
struct Node_base : Balance { .. };

template <typename Val, typename Balance>
struct Search_node : Node_base<Search_node<Val, Balance>, Balance> { .. };

关于C++ 泛型编程 CRTP 基类继承自派生类型提供的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28178518/

相关文章:

c++ - 删除单例对象时内存泄漏,cpp

c++ - Boost spirit 将整个比赛作为一个字符串

templates - CheckBoxList 多选 : how to model bind back and get all selections?

c++ - 如何从双参数模板创建单参数模板以用作基类模板模板参数

c++ - 我怎样才能初始化这个结构?

数组中的 C++ CRTP

c++ - 调用 ~Derived() 和 ~Base() 之间的对象状态

c++ - 从基调用访问派生 crtp 类的函数

c++ - CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc

c++ - 错误 C2440 : 'initializing' : cannot convert from 'const wchar_t [9]' to 'LPCSTR'