我正在尝试使用 C++11 功能来更轻松地创建自定义流操纵器。我可以使用 lambda 函数作为操纵器,但不能 std::function<ostream&(ostream&)>
.
这是代码,归结起来:
#include <iostream>
#include <functional>
using namespace std;
auto lambdaManip = [] (ostream& stream) -> ostream& {
stream << "Hello world" << endl;
};
function<ostream& (ostream&)> functionManip = [] (ostream& stream) -> ostream& {
stream << "Hello world" << endl;
};
int main (int argc, char** argv) {
cout << lambdaManip; // OK
cout << functionManip; // Compiler error
}
第二个cout
语句失败并显示以下内容:
g++-4 src/Solve.cpp -c -g -std=c++0x -o src/Solve.o -I/home/ekrohne/minisat
src/Solve.cpp: In function 'int main(int, char**)':
src/Solve.cpp:24:11: error: cannot bind 'std::ostream' lvalue to 'std::basic_ostream<char>&&'
/usr/lib/gcc/i686-pc-cygwin/4.5.3/include/c++/ostream:579:5: error: initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char, _Traits = std::char_traits<char>, _Tp = std::function<std::basic_ostream<char>&(std::basic_ostream<char>&)>]'
为什么会失败?我正在使用 cygwin gcc 4.5.3。
虽然我在问,但我并不疯狂使用 std::function
无处不在,由于效率问题。但我确实希望编写返回 lambda 函数的函数,并且不知道如何在没有 std::function
的情况下这样做.例如,像下面这样的东西会很棒
auto getAdditionFunctor();
auto getAdditionFunctor() {
return [] (int x, int y) { return x + y };
};
...但显然行不通。是否有其他有效的语法?我无法想象它会是什么,所以我可能会被 std::function
困住。 .
如果我有第二个问题的答案,那么第一个问题就没有实际意义了。
谢谢。
定义 operator<<(ostream&, std::function<ostream&(ostream&)>
帮助。我误读了一个网页,印象中 ostream
足够聪明,可以处理具有 operator()
的任意对象作为操纵者。我错了。此外,简单的 lambda
正如我被告知的那样,我构建的可能只是被编译成一个普通的旧函数。事实上,如果我使用变量捕获来确保 lambda
不是简单函数,则编译器失败。此外,带有 operator()
的对象defined 不(默认情况下)被视为操纵器:
class Manipulator {
ostream& operator()(ostream& stream) const {
return stream << "Hello world" << endl;
};
} classManip;
function<ostream& (ostream&)> functionManip = [] (ostream& stream) -> ostream& {
return stream << "Hello world" << endl;
};
int main (int argc, char** argv) {
const string str = "Hello world";
auto lambdaManip = [&] (ostream& stream) -> ostream& {
return stream << str << endl;
};
cout << classManip; // Compiler error
cout << lambdaManip; // Compiler error
cout << functionManip; // Compiler error
}
进一步更新:事实证明这是一个比下面的解决方案更强大的解决方案:
// Tell ostreams to interpret std::function as a
// manipulator, wherever it sees one.
inline ostream& operator<<(
ostream& stream,
const function<ostream& (ostream&)>& manipulator) {
return manipulator( stream );
}
这段代码有一个额外的const
.我发现这是为了在我的项目中实际实现解决方案。
最佳答案
如果你看operator<<
对于 ostream
, 没有重载 std::function
- 这基本上就是您在这里尝试用 cout << functionManip
做的事情.要解决此问题,请自行定义重载:
ostream& operator<<(ostream& os, std::function<ostream& (ostream&)>& s)
{
return s(os);
}
或者传递stream
作为函数的参数:
functionManip(std::cout);
至于为什么lambda
正在工作,因为 lambda
的返回类型是未定义的,并且有一个使用函数指针的重载:
ostream& operator<< (ostream& ( *pf )(ostream&));
lambda 可能使用结构包装所有内容并定义 operator()
在这种情况下,它将完全像函数指针一样工作。这对我来说是最可能的解释,如果我错了,希望有人能纠正我。
关于c++ - std::function 作为自定义流操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003645/