gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:43 25 4
gpt4 key购买 nike

阅读 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com