std :: enable_shared_from_this的CRTP

问题描述 投票:0回答:1

例如,我有一个具体的AST节点:

class BinaryOp: public ASTNode, std::enable_shared_from_this<BinaryOp>
{
public:
    BinaryOp(const ASTNodePtr& lhs, Token::Type op, const ASTNodePtr& rhs) noexcept;
    void accept(const IASTNodeVisitorPtr& visitor) override { visitor->visit(this->shared_from_this());}
    Token::Type op;
};

从基类std :: enable_shared_from_this mixin继承并编写对所有派生类都相同的accept函数很麻烦。

我写了这样的东西

template <typename Node>
class ConcreteASTNode: public ASTNode, std::enable_shared_from_this<Node>
{
public:
    void accept(const IASTNodeVisitorPtr& visitor) override { visitor->visit(Node::shared_from_this());}
};

class BinaryOp: public ConcreteASTNode<BinaryOp>
{
...
};

但是那不起作用,因为我遇到了bad_weak_ptr异常。我发现了一个类似的问题,但没有为我提供任何答案。

是否有解决此问题的方法,或者是设计问题?

c++ virtual-functions crtp enable-shared-from-this
1个回答
0
投票
之间有区别

class BinaryOp: public ASTNode, std::enable_shared_from_this<BinaryOp>

© www.soinside.com 2019 - 2024. All rights reserved.