Question

If my question is confusing, what I basically mean is this:

in java if you System.out.println(class) it will default to the toString function and prints what ever is specified there. I was wondering if I could do something like that in C++. I should also probably mention I am not too good at c++ so there may be many errors in my example code.

class thing  {
    private:
            char *foo;
    public:
            thing(){   foo="asd";   }
            char* getString(){   return foo;   }
            friend ostream& operator<<(ostream &out, thing &abc);
    };

    template<typename T>
    ostream& operator<<(ostream &out, T &abc){
            out<<abc.getString();
            return out;   }


int main(){
            thing test;
            cout<<test;
            return 0;  }

I've tried to do this a few ways and I always get some kind of error.

Was it helpful?

Solution 2

this is working version of your code, combined with @Mooing Duck's SFINAE check

#include <iostream>
#include <ostream>

using namespace std;

class thing  {
private:
        const char *foo;
public:
        thing(){   foo="asd";   }
        const char* getString() const {   return foo;   }
};

template<typename T, class = decltype(std::cout<<std::declval<T>().getString())>
ostream& operator<<(ostream &out, T const &abc){
    out<<abc.getString();
    return out;
}

int main(){
    thing test;
    cout<<test << 3;
    return 0;
}

live demo

OTHER TIPS

The basic idea is okay. Though, arguably you've simply shifted the dependency from having an << overload to having the getString() member. You should pass by const-ref, though. Also, getString() should be const.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top