majintao0131 / yaml-cpp

Automatically exported from code.google.com/p/yaml-cpp
MIT License
0 stars 0 forks source link

operator overloading doesn't work for pointers #57

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
When I overload << to output a reference to my class, YAML works fine, but
when I overload << to output a pointer to my class, YAML prints true if the
pointer is non-null and false otherwise

example:
(using mingw g++)

source:

class foo {
public:
    std::string bar() const {
        return std::string("foobar!");
    }
};

std::ostream& operator << (std::ostream& out, const foo &f) {
    return out << f.bar();
}
std::ostream& operator << (std::ostream& out, const foo* f) {
    std::cout << "pointer operator called\n";
    if (f == NULL) {
        return out << "NULL";
    } else {
        return out << (*f);
    }
}

YAML::Emitter& operator << (YAML::Emitter& out, const foo &f) {
    return out << f.bar();
}
YAML::Emitter& operator << (YAML::Emitter& out, const foo *f) {
    std::cout << "pointer operator called\n";
    if (f == NULL) {
        return out << "NULL";
    } else {
        return out << (*f);
    }
}

int main(int argc, char**argv) {
    foo f;
    std::cout << f << "\n";
    foo *g = &f;
    std::cout << g << "\n";
    g = NULL;
    std::cout << g << "\n";

    YAML::Emitter out;
    out << YAML::BeginSeq;
    out << f;
    g = &f;
    out << g;
    g = NULL;
    out << g;
    out << YAML::EndSeq;

    std::cout << out.c_str() << "\n";

    return 0;
}

output:

foobar!
pointer operator called
foobar!
pointer operator called
NULL
- foobar!
- true
- false

Otherwise, so far so good; this code is a huge help.

Thanks,
Marc

Original issue reported on code.google.com by gers...@gmail.com on 13 Nov 2009 at 8:48

GoogleCodeExporter commented 9 years ago
Interesting! I never thought about this possibility. What's happening is that 
when
you call

    emitter << ptr;

it first tries to instantiate the templated `operator << ` in the `YAML` 
namespace
(since `emitter` is a member of that namespace), and succeeds, with a 
conversion of
`foo *` to `bool`, and so never looks for an `operator <<` in the global 
namespace.
I'll see what I can do about this.

Original comment by jbe...@gmail.com on 13 Nov 2009 at 9:48

GoogleCodeExporter commented 9 years ago
Thanks!
I try to put pointers to objects in my containers, so being able to overload 
the <<
operator for pointer types would be really nice.

Original comment by gers...@gmail.com on 17 Nov 2009 at 6:59

GoogleCodeExporter commented 9 years ago
In r325, it should be possible to overload operator << for pointers. I'm 
considering
adding such a templated function for pointer types, but I'm not sure about it.

Let me know if this works for you.

Original comment by jbe...@gmail.com on 17 Nov 2009 at 8:22