#variant issues w/ unique_ptr

17 messages · Page 1 of 1 (latest)

rapid plinthBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

smoky vector
#

i get these errors when i try to do the following:

#
void Generator::gen_stmt(Stmt stmt)
{
    struct StmtVisitor {
        Generator& gen;

        void operator()(VarStmt var_stmt)
        {
        }
    };

    StmtVisitor stmt_visitor{*this};
    std::visit(stmt_visitor, stmt.m_stmt);
}
#

this is the entire ast

struct Expr;

struct VarStmt {
    std::string m_name{};
    std::unique_ptr<Expr> m_expr{};
};

struct Stmt {
    std::variant<VarStmt> m_stmt{};
};

struct IntExpr {
    int m_value{};
};

struct FloatExpr {
    float m_value{};
};

struct StrExpr {
    std::string m_value{};
};

struct AtomExpr {
    std::variant<IntExpr, FloatExpr, StrExpr> m_atom{};
};

struct BinOpExpr {
    std::unique_ptr<Expr> m_lhs{};
    std::unique_ptr<Expr> m_rhs{};
    Token_Type m_op{};
};

struct Expr {
    std::variant<AtomExpr, BinOpExpr> m_expr{};
};

struct Program {
    std::vector<Stmt> m_body{};
};
#

okay, i needed to take VarStmt& instead of VarStmt as an argument

#

but I don't understand why

proper crown
#

You can't copy a unique_ptr

#

You can move it with std::move or pass by reference

smoky vector
proper crown
#

Some?

smoky vector
#

the function has to accept a reference to a Stmt

#

so that Stmt is not copied

#

as it contains a variant that contains a uniqueptr

proper crown
#

Yep exactly

jaunty thistle
#

U have to implement
void operator()( VarStmt &var_stmt)
{

}
Instead of
void operator()(VarStmt var_stmt)
{

}

#

The error occurs because VarStmt uses an overloaded operator that takes an argument as a value, and std::visit provides an argument by reference (VarStmt&)