1

我有一个静态变量 ,nil它充当template <typename Node> Tree. 我通过专注于类型来增加我的树。Node但是,我在构建 nil 时遇到了麻烦。

Nil 作为 Tree 的静态成员

里面tree.h

template <typename Node>
class Tree {
    using NP = Node*;
    using T = typename Node::key_type;

    NP root {nil};
    // nil sentinel
    static NP nil;

    // core utilities
    const static NP get_nil() {
        return nil;
    }
};

enum class Color : char {BLACK = 0, RED = 1};

template <typename T>
struct Basic_node {
        using key_type = T;
        T key;
        Basic_node *parent, *left, *right;
        Color color;
        Basic_node() : color{Color::BLACK} {}   // sentinel construction
        Basic_node(T val, Color col = Color::RED) : 
            key{val}, 
            parent{Tree<Basic_node>::get_nil()}, 
            left{Tree<Basic_node>::get_nil()}, 
            right{Tree<Basic_node>::get_nil()}, 
            color{col} {}
};

template <typename T>
using Basic_tree = Tree<Basic_node<T>>;

template <typename T>
typename Basic_tree<T>::NP Basic_tree<T>::nil {new Basic_node<T>};
// alternatively
template <typename T>
Basic_node<T>* Basic_tree<T>::nil {new Basic_node{}};

错误 template definition of non-template 'typename sal::Basic_tree<T>::NP sal::Tree<sal::Basic_node<T> >::nil' 发生在最后两行。

Basic_node我希望将相同的 nil 用于与每种 T 类型一起使用的所有树。

Nil 作为 Node 的静态成员

然后我尝试使 nil 成为Basic_node. 这样节点不依赖于树(这parent{Tree<Basic_node>::get_nil()}真的很讨厌)并且更自然。

template <typename T>
struct Basic_node {
        static Basic_node* nil;

        using key_type = T;
        T key;
        Basic_node *parent, *left, *right;
        Color color;
        Basic_node() : color{Color::BLACK} {}   // sentinel construction
        Basic_node(T val, Color col = Color::RED) : key{val}, parent{nil}, left{nil}, right{nil}, color{col} {}
};
template <typename T>
Basic_node<T>* Basic_node<T>::nil {new Basic_node{}};

// inside Tree
using Node::nil;

新错误type 'sal::Basic_node<int>' is not a base type for type 'sal::Tree<sal::Basic_node<int> >'意味着我在滥用using,因为它假设我指的是层次结构。我在这里的意思是当我在 Tree 的其余部分Node::nil提到时使用。nil

请注意,我的最后一种方法有效,只是我每次都必须引用 Node::nil;另外,我很好奇 Node::nil 是否引入了任何额外的间接性)。

4

0 回答 0