C ++ Manipulator Fails

Well, I wonder why enddit doesn't seem to be executed (although it does not generate errors at compile time).

struct dxfDato
{
    dxfDato(int c, string v = 0, int t = 0) { codigo = c; valor = v; tipo = t; }
    dxfDato() { }

    int tipo;
    int codigo;
    string valor;
};
class dxfItem
{
private:
    std::ostringstream ss;
    typedef std::ostream& (*manip)(std::ostream&);

public:
    int clase;
    string valor;
    vector<dxfDato> datos;
    vector<dxfItem> hijos;

    template <typename T>
    dxfItem& operator<<(const T& x)
    {
        ss << x;
        return *this;
    }
    dxfItem& operator<<(manip x) // to store std manipulators
    {
        ss << x;
        return *this;
    }
    static dxfItem& endd(dxfItem& i) // specific manipulator 'endd'
    {
        dxfDato dd;
        dd.valor = i.ss.str();
        i.datos.push_back(dd);

        std::cout << "endd found!" << endl;
        return i;
    }
};

/* blah blah blah */

dxfItem header;

header
    << 9 << endl << "$ACADVER" << endl << 1 << endl << "AC1500" << endl
    << dxfItem::endd // this apparently doesn't execute anything
    << "other data" << endl
;

This is the last problem I found while trying to develop something. The latter was shown here: C ++ operator overload example

Thanks everyone!

+3
source share
7 answers

You defined the type manipas a function that takes std::ostreamby reference and returns std::ostreamby reference, but you defined enddto take dxfItemand return dxfItemand is dxfItemnot inferred from std::ostream.

Because of this type of inconsistency, the compiler generates a call to the pattern operator<<, not an overload manip.

, manip :

dxfItem& operator<<(manip x)
{
   x(ss);
   return *this;
}

a >

+4

, endd, , endl. endl - , . , ( ).

( , endd , google " ++"...)

+1

, std::ostream& (*)(std::ostream& strm).

, ++ .

+1

, , , , , :

typedef dxfItem& (*noArgdxfManip)(dxfItem &); // here is the type for your manipulator

dxfItem & operator << (noArgdxfManip manip)
{
    return manip(*this);
}

, , . , , < , . , , , , . dxfItem.

, .

+1

, < , .

typedef overloaded < , , ostream &.

< < , dxfItem &, < < / , .

typedef :

typedef dxfItem& (*endd_manip)(dxfItem&);

< < :

dxfItem& operator<<(endd_manip x)
{
    // Call the manipulator on the stream.
    x(*this);

    return *this;
}
+1
source

I think my problem is that this line

    << dxfItem::endd // this apparently doesn't execute anything

There must be something like this

<< dxfItem::endd(Whatever argument goes in here) 
0
source

Functions in C ++ (as in C) are called ("executed") by a function call operator ()(which can also provide function arguments). I do not see function statements in your code applied to a function endd, directly or indirectly. That is why it is never executed.

-1
source

Source: https://habr.com/ru/post/1731391/


All Articles