global operator <<

Hi

If you had to replace the following member function with a (global) operator <<, how would you do that?

1
2
3
4
5
6
  void print(vector<string> &names, vector<double> &ages){
    cout << endl;
    for (int j=0; j<names.size(); j++){
        cout << names.at(j) << ", " << ages.at(j) << endl;
    }
}


Regards
Jason McG
The operator << has an arity of two: stm << object ;
So we need to wrap (references to) the two objects into a single holder object
(which becomes the second argument for the binary operator).

Something along these lines:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <vector>

template < typename A, typename B > struct wrapper_t
{
     const A& first ;
     const B& second ;
};

template < typename A, typename B >
wrapper_t<A,B> wrap( const A& first, const B& second ) { return { first, second } ; }

template < typename SEQA, typename SEQB >
std::ostream& operator<< ( std::ostream& stm, const wrapper_t<SEQA,SEQB>& wrapper )
{
    for( std::size_t i = 0 ; i < wrapper.first.size() ; ++i )
        stm << wrapper.first[i] << ", " << wrapper.second.at(i) << '\n' ;
    return stm ;
}

int main()
{
    const std::vector<std::string> names { "felix", "fido", "silver", "daffy", "button" } ;
    const std::vector<double> ages { 2.3, 1.8, 3.2, 2.1, 0.7 } ;

    std::cout << wrap( names, ages ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/199b970524897679
Topic archived. No new replies allowed.