如何在 C++ 中将 ostream 运算符<< 作为函数传递?

Ric*_*yen 3 c++

有什么方法可以std::ostream operator<<在其他函数调用中传递 an 作为参数吗?例如:

\n
\n#include <iostream>\n\ntemplate <typename Visitor>\nvoid print(Visitor v, int value)\n{\n    v(value);\n}\n\nint main(void)\n{\n\n    std::cout.operator<<(5); // This works\n\n    std::cout << 5; // This works\n\n    print(std::cout.operator<<, 5); // Error happens\n\n    return 0;\n}\n\n
Run Code Online (Sandbox Code Playgroud)\n

错误是:

\n
$ g++ -g main.cpp -o main\nmain.cpp: In function \xe2\x80\x98int main()\xe2\x80\x99:\nmain.cpp:17:12: error: no matching function for call to \xe2\x80\x98print(<unresolved overloaded function type>, int)\xe2\x80\x99\n           5);\n            ^\nmain.cpp:4:6: note: candidate: template<class Visitor> void print(Visitor, int)\n void print(Visitor v, int value)\n      ^~~~~\nmain.cpp:4:6: note:   template argument deduction/substitution failed:\nmain.cpp:17:12: note:   could not deduce template parameter "Visitor"\n\n
Run Code Online (Sandbox Code Playgroud)\n

我知道在 C++ 中我们可以进行运算符重载std::ostream& operator<<(std::ostream& out, something);,但这不是我的目标。假设我想使用其他打印函数或运算符(例如std::foutprintf),所以我希望我的print函数尽可能通用。

\n

son*_*yao 8

您可以改为传递 lambda。

print([](int value) { std::cout << value; }, 5);
Run Code Online (Sandbox Code Playgroud)