4

I have this example on class templates and friends:

template <typename T>
class Foo;

template <typename T>
std::ostream& operator<<(std::ostream&, Foo<T> const&);

template <typename T>
std::istream& operator>>(std::istream&, Foo<T>&);

template <typename T>
class Foo{
private:
    int x = 10;
    friend std::ostream& operator<< <T>(std::ostream&, Foo const&);
    friend std::istream& operator>> <>(std::istream&, Foo&);
};

template <typename T>
std::ostream& operator<<(std::ostream& os, Foo<T> const& f){
    return os << f.x;
}

template <typename T>
std::istream& operator>>(std::istream& is, Foo<T>& f){
    return is >> f.x;
}


int main(){

    Foo<double> fd;
    std::cin >> fd;
    std::cout << fd << '\n';

    std::cout << '\n';
}
  • The wroks fine but I want to know the difference between the insertion operator << friendship type and the extraction operator >> friendship type to class Foo.

  • Does ...operator<< <T>.. that each instantiation of the output operator for the same type used to instantiate Foo is its friend? So Is this One-To-One friendship?

  • What confuses me is the extraction operator: operator >> <>(...: What does this mean? Is this a full specialization?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Itachi Uchiwa
  • 3,044
  • 12
  • 26

1 Answers1

2

The wroks fine but I want to know the difference between the insertion operator << friendship type and the extraction operator >> friendship type to class Foo.

They have the same effect here.

Does ...operator<< <T>.. that each instantiation of the output operator for the same type used to instantiate Foo is its friend? So Is this One-To-One friendship?

Yes. For Foo<double>, only operator<< <double> and operator>> <double> are friends.

What confuses me is the extraction operator: operator>> <>(...: What does this mean? Is this a full specialization?

Template argument deduction is performed to determine the type T (based on the 2nd function parameter; Foo is same as Foo<T>), then the friend declaration refers to the instantiation for the deduced T. It's just same as specifying template argument T as operator>> <T>(....

songyuanyao
  • 169,198
  • 16
  • 310
  • 405