二进制表达式的无效操作数('ostream'(又名'basic_ostream <char>')和'ostream')</char>

时间:2013-11-17 09:29:31

标签: c++

我正在尝试

cout << Print(cout);然而,在编译时会出现“二进制表达式无效的操作数('ostream'(又名'basic_ostream')和'ostream')”错误。

#include <iostream>

using namespace std;

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

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

为什么这不起作用? 我怎样才能解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:5)

您可能正在寻找的语法是std::cout << Print << " and hello again!\n";。函数指针被视为操纵器。内置operator <<将指针指向Print,并使用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;
}

答案 1 :(得分:4)

这是您的第二个请求:

#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);
}