我坚持使用这种模式,因为仅实例化了我创建的一个派生类。已通过g ++和MSVS检查。具体而言,仅创建我定义的第一个派生类。编译器不会发出任何警告。下面提供了完整的代码。

#include <iostream>

static int nodes = 0;

class TreeNode {
private:
    int m_id;
public:
    TreeNode() :
        m_id(++nodes)
    {}
    TreeNode(int id) :
        m_id(id)
    {
        ++nodes;
    }
    TreeNode* left;
    TreeNode* right;

    int getId() const {
        return m_id;
    }
};


template<typename T>
//typename std::enable_if<std::is_base_of<TreeParser, T>::value>::type
class TreeParser {
protected:
    TreeParser() {
        ++parsers;
    }
public:
    static uint32_t parsers;
    void preorderTraversal(TreeNode* node) {
        if (node != nullptr) {
            processNode(node);
            preorderTraversal(node->left);
            preorderTraversal(node->right);
        }
    }
    virtual ~TreeParser() = default;

    void processNode(TreeNode* node) {              // 2, 3. the generic algorithm is customized by derived classes
        static_cast<T*>(this)->processNode(node);   // depending on the client's demand - the right function will be called
    }
};

template<class T>
uint32_t TreeParser<T>::parsers = 0;

class SpecializedTreeParser1 : public TreeParser<SpecializedTreeParser1> // 1. is-a relationship
{
public:
    explicit SpecializedTreeParser1() :
        TreeParser()
    {}
    void processNode(TreeNode* node) {
        std::cout << "Customized (derived - SpecializedTreeParser1) processNode(node) - "
            "id=" << node->getId() << '\n';
    }
};

class SpecializedTreeParser2 : public TreeParser<SpecializedTreeParser2> // 1. is-a relationship
{
public:
    explicit SpecializedTreeParser2() :
        TreeParser()
    {}
    void processNode(TreeNode* node) {
        std::cout << "Customized (derived - SpecializedTreeParser2) processNode(node) - "
            "id=" << node->getId() << '\n';
    }
};


int main()
{
    TreeNode root;
    TreeNode leftChild;
    TreeNode rightChild;

    root.left = &leftChild;
    root.right = &rightChild;

    std::cout << "Root id: " << root.getId() << '\n';
    std::cout << "Left child id: " << leftChild.getId() << '\n';
    std::cout << "Right child id: " << rightChild.getId() << '\n';

    SpecializedTreeParser1 _1;
    _1.preorderTraversal(&root);

    SpecializedTreeParser2 _2;
    _2.preorderTraversal(&root);
}


输出为:

Root id: 1
Left child id: 2
Right child id: 3
Customized (derived - SpecializedTreeParser1) preorderTraversal() - id=1
Customized (derived - SpecializedTreeParser1) preorderTraversal() - id=2
Customized (derived - SpecializedTreeParser1) preorderTraversal() - id=1963060099 // what is that?


为什么不能实例化第二个派生类?

最佳答案

我没记错,您的程序具有未定义的行为。 leftrightleftChildrightChild指针未初始化,因此,一旦preorderTraversal()到达该位置,程序就会崩溃。这就是为什么最后得到奇怪的id的原因:它是从某个随机内存位置读取的…

要解决此问题,请确保将leftrightTreeNode成员始终初始化为nullptr,这与其余代码似乎期望的一样:

class TreeNode {
    …
    TreeNode* left = nullptr;
    TreeNode* right = nullptr;
    …
};

09-06 17:56