0

Here's a test class for demonstrating what I mean.

#include <iostream>

template <typename T>
class Test
{
public:
    int s;
    friend std::istream& operator>>(std::istream& input, Test<T>& test1);
    friend std::ostream& operator<<(std::ostream& output, const Test<T>& test1);
};

template <typename T>
std::istream& operator>>(std::istream& input, Test<T>& test1)
{
    input >> test1.s;
    return input;
}

template <typename T>
std::ostream& operator<<(std::ostream& output, const Test<T>& test1)
{
    output << test1.s;
    return output;
}

int main()
{
    Test<int> clasaTest;
    std::cin >> clasaTest;
    std::cout << clasaTest;
}

photo

If I rewrite it like this

template <typename T>
class Test
{
public:
    int s;
    template <typename U>
    friend std::istream& operator>>(std::istream& input, Test<U>& test1);
    template <typename U>
    friend std::ostream& operator<<(std::ostream& output, const Test<U>& test1);
};

it will work properly, but I can't really understand why.

Shouldn't it work with the same T declared before? Because the class will have the same generic argument?

  • 1
    For future questions, please copy-paste build errors *as text*. Images can't be searched, can't be used by screen readers, can't be copy-pasted from, and are very often hard to read or decipher. – Some programmer dude Jun 28 '21 at 14:37
  • @Someprogrammerdude I'm sorry, I didn't realise that. –  Jun 28 '21 at 15:11

1 Answers1

3

friend std::istream& operator>>(std::istream&, Test<T>&);

and

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

are unrelated functions (the former is non-template contrary to the later).

Simplest fix would be inline definition:

template <typename T>
class Test
{
public:
    int s;
    friend std::istream& operator>>(std::istream& input, Test& test1)
    {
        input >> test1.s;
        return input;
    }

    friend std::ostream& operator<<(std::ostream& output, const Test& test1)
    {
        output << test1.s;
        return output;
    }

};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • For the OP's example code, they don't even need to be friends because of the member variable is public (ick ick, ptui ptui). But in the general case with private or protected member variables, this is the expedient approach. – Eljay Jun 28 '21 at 14:36
  • @Eljay yes, it was just a quick demo made in a rush to show you what I mean and I forgot to declare s as private. –  Jun 28 '21 at 15:13