Karish Karish
Karish Karish

Reputation: 269

c++ templates and overloading operators

I am trying to understand how this program works. i am new to c++ templates. Can someone explain why we need the following function?

friend std::ostream &operator <<(std::ostream &os, const Temp &temp)

It seems to work only for the string template.

Also, what does the function operator T() {return val;} do?

#include <iostream>
#include<string>

template <typename T>
class Temp {        
    friend std::ostream &operator <<(std::ostream &os, const Temp &temp) {
    os << temp.val;
    return os;
    }

public:
    Temp(T val) : val(val) {}
    operator T() {return val;}
public:
    T val;
};

usage example:

#include <iostream>
#include<string>

#include "temp2.h"

using namespace std;

int main() {
    temp<int> si = 10;
    cout << "si: " << si << endl;
    si = si + 2;
    cout << "After si = si + 2: " << si << endl;

    Temp<double> si2 = 15.5;
    cout << "si: " << si2 << endl;
    si2 = si2 + 2.3;
    cout << "After si = si + 2: " << si2 << endl;

    Temp<string> ss = string("Hello");
    cout << "ss: " << ss << endl;
    ss = string(ss).substr(1);
    cout << "After ss = si.substr(1): " << ss << endl;

    return 0;
}

Upvotes: 0

Views: 150

Answers (1)

didierc
didierc

Reputation: 14730

It's not that the operator << is really needed, but it's convenient to have it when using output streams. Also, the operator needs to access the inner value of the Temp class, hence the friend qualifier. Without it, the class would have to expose the inner value val to the external world somehow (the usual way is to make a public read only method), and this create a maintenance problem, since future evolutions of the class would have to keep supporting the method, even if the class internals change.

In other words, having the << operator declared as friend to the class prevents the implementation details to leak out to the rest of the world.

That said, the T() operator provides almost the service of the hypothetic read only method that I described above, but with replacing the read only part by copying the val field. Basically, it's a cast operator allowing to implicitely cast a Temp value to a T value. The << operator could have been implemented using that cast operator, and thus without the need of the friend qualifier. However, certainly for efficiency concerns, the friend qualifier has been kept to avoid the overhead of copying val.

Regarding the implementation of the << operator, we can see that it rely on the same operator defined for the T typename. Any type having this operator defined for should work without problem with this template.

Upvotes: 1

Related Questions