dimanche 2 juillet 2017

Is it possible to somehow call this.get() on std::shared_ptr in c++?

Code without std::shared_ptr works correctly:

class Visitor;
class Red
{
public:
    void accept(Visitor *v);
};
class Visitor
{
public:
    virtual void visit(Red *v) = 0;
};
class CountVisitor: public Visitor
{
public:
    void visit(Red *v) {}
};
void Red::accept(Visitor *v)
{
    v->visit(this);
}
int main()
{
    Red r;
    Visitor *v = new CountVisitor();
    r.accept(v);
}

Exactly the same code with std::shared_ptr does not work correctly. Is it possible to run something like this.get() on std::shared_ptr or somehow call this on function/method with std::shared_ptr as an argument? Code with std::shared_ptr:

#include <memory>
class Visitor;
class Red
{
public:
    void accept(const std::shared_ptr<Visitor> &v);
};
class Visitor
{
public:
    virtual void visit(const std::shared_ptr<Red> &v) = 0;
};
class CountVisitor: public Visitor
{
public:
    void visit(const std::shared_ptr<Red> &v) {}
};
void Red::accept(const std::shared_ptr<Visitor> &v)
{
    v->visit(this);//somehow this.get() to get data pointer of shared_ptr
}
int main()
{
    Red r;
    r.accept(std::make_shared<CountVisitor>());
}

Aucun commentaire:

Enregistrer un commentaire