在处理这个问题的过程中,我注意到GCC(v4.7)的实现std::function在它们被值出现时会移动它的论点.以下代码显示了此行为:
#include <functional>
#include <iostream>
struct CopyableMovable
{
CopyableMovable() { std::cout << "default" << '\n'; }
CopyableMovable(CopyableMovable const &) { std::cout << "copy" << '\n'; }
CopyableMovable(CopyableMovable &&) { std::cout << "move" << '\n'; }
};
void foo(CopyableMovable cm)
{ }
int main()
{
typedef std::function<void(CopyableMovable)> byValue;
byValue fooByValue = foo;
CopyableMovable cm;
fooByValue(cm);
}
// outputs: default copy move move
Run Code Online (Sandbox Code Playgroud)
我们在这里看到cm执行的副本(这似乎是合理的,因为byValue's参数是按值获取的),但是有两个动作.由于它function是在副本上运行cm,它移动其参数的事实可以被视为一个不重要的实现细节.但是,与以下一起使用时functionbind …
编辑:我在下面使用咖喱,但已被告知这是部分申请.
我一直想弄清楚如何在C++中编写咖喱函数,我实际上已经弄明白了!
#include <stdio.h>
#include <functional>
template< class Ret, class Arg1, class ...Args >
auto curry( Ret f(Arg1,Args...), Arg1 arg )
-> std::function< Ret(Args...) >
{
return [=]( Args ...args ) { return f( arg, args... ); };
}
Run Code Online (Sandbox Code Playgroud)
我也为lambdas写了一个版本.
template< class Ret, class Arg1, class ...Args >
auto curry( const std::function<Ret(Arg1,Args...)>& f, Arg1 arg )
-> std::function< Ret(Args...) >
{
return [=]( Args ...args ) { return f( arg, args... ); };
}
Run Code Online (Sandbox Code Playgroud)
测试:
int f( int x, int …Run Code Online (Sandbox Code Playgroud)