JASON
JASON

Reputation: 7491

invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream')

I'm trying to do

cout << Print(cout); However, there is an "invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'ostream')" error when compiling.

#include <iostream>

using namespace std;

ostream& Print(ostream& out) {
  out << "Hello World!";
  return out;
}

int main() {
  cout << Print(cout);
  return 0;
}

Why this doesn't work? How can I fix this? Thanks!!

Upvotes: 8

Views: 51712

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137810

The syntax you might be looking for is std::cout << Print << " and hello again!\n";. The function pointer is treated as a manipulator. A built-in operator << takes the pointer to Print and calls it with cout.

#include <iostream>

using namespace std;

ostream& Print(ostream& out) {
  out << "Hello World!";
  return out;
}

int main() {
  cout << Print << " and hello again!\n";
  return 0;
}

Upvotes: 8

David G
David G

Reputation: 96810

Here is your second request:

#include <iostream>
#include <vector>
#include <iterator>

template <class Argument>
class manipulator
{
private:
    typedef std::ostream& (*Function)(std::ostream&, Argument);
public:
    manipulator(Function f, Argument _arg)
        : callback(f), arg(_arg)
    { }

    void do_op(std::ostream& str) const
    {
        callback(str, arg);
    }
private:
    Function callback;
    Argument arg;
};

template <class T>
class do_print : public manipulator<const std::vector<T>&>
{
public:
    do_print(const std::vector<T>& v)
        : manipulator<const std::vector<T>&>(call, v) { }

private:

    static std::ostream& call(std::ostream& os, const std::vector<T>& v)
    {
        os << "{ ";
        std::copy(v.begin(), v.end(),
                     std::ostream_iterator<T>(std::cout, ", "));
        return os << "}";
    }
};

template <class Argument>
std::ostream& operator<<(std::ostream& os, const manipulator<Argument>& m)
{
    if (!os.good())
        return os;

    m.do_op(os);
    return os;
}

template<class T>
do_print<T> Print(const std::vector<T>& v)
{
    return do_print<T>(v);
}

int main()
{
    std::vector<int> v{1, 2, 3};
    std::cout << Print(v);
}

Upvotes: 5

Related Questions