I have a complex object that I want to be able to pass into a std::ostringstream with the << operator just like a string or int. I want to give the ostringstream the object's unique id (int) and/or name (string). Is there an operator or method I can implement in my class to allow this to work?
            Asked
            
        
        
            Active
            
        
            Viewed 5,599 times
        
    2
            
            
         
    
    
        Mar
        
- 7,765
- 9
- 48
- 82
- 
                    5Yes just overload the << operator - see http://stackoverflow.com/questions/4421706/operator-overloading – Martin Beckett Jun 05 '12 at 22:01
- 
                    1unique id in what context? In an instance of running process you could use it's memory address. – Ivarpoiss Jun 05 '12 at 22:02
- 
                    They are "Student" objects, for a class project. Each Student object has a name, id, address, and phone number, and are built from a txt file. – Mar Jun 05 '12 at 22:09
- 
                    @MartinBeckett - overload << for my class, or for `ostringstream`? – Mar Jun 05 '12 at 22:10
- 
                    @mouseas - for your class. Each class simply has a function that is called when you ask for '<<' which prints the values. It's just that for int/float/double etc they are built-in – Martin Beckett Jun 05 '12 at 22:11
- 
                    Well, make an answer, then. What should the return be? – Mar Jun 05 '12 at 22:15
1 Answers
4
            Define an operator overload in the same namespace as your class:
template<typename charT, typename traits>
std::basic_ostream<charT, traits> &
operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
    return lhs << rhs.id() << ' ' << rhs.name();
}
If the output function needs access to private members of your class then you can define it as a friend function:
class Your_class {
    int id;
    string name;
    template<typename charT, typename traits>
    friend std::basic_ostream<charT, traits> &
    operator<< (std::basic_ostream<charT, traits> &lhs, Your_class const &rhs) {
        return lhs << rhs.id << ' ' << rhs.name;
    }
};
Note that this does not result in a member function, it's just a convenient way to declare and define a friend function at once.
 
    
    
        bames53
        
- 86,085
- 15
- 179
- 244
- 
                    1The `traits` template parameter has a default value, so it can be skipped. – AlwaysLearning Dec 09 '15 at 11:51