C++ Manipulator not being executed

c

Well, I'm wondering why endd doesn't seem to execute (though it doesn't generate any error at compilation 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 that I found while trying to develop something. Last thing was exposed here: C++ Operator overloading example

Thank you all!

Best Answer

You've defined type manip to be a function that takes a std::ostream by reference and returns a std::ostream by reference, but you've defined endd to take a dxfItem and return a dxfItem and dxfItem does not derive from std::ostream.

Because of this type mismatch, the compiler is generating a call to the operator<< template, rather than the manip overload.

Also, your manip overload needs to actually call the manipulator function passed into it:

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

Related Topic