在我们的代码中,我们有很多这种模式的情况:
class outerClass
{
struct innerStruct
{
wstring operator()( wstring value )
{
//do something
return value;
}
};
void doThing()
{
wstring initialValue;
wstring finalValue = innerStruct()( initialValue );
}
};
Run Code Online (Sandbox Code Playgroud)
这有什么好处:
class outerClass
{
wstring changeString( wstring value )
{
//do something
return value;
}
void doThing()
{
wstring initialValue;
wstring finalValue = changeString( initialValue );
}
};
Run Code Online (Sandbox Code Playgroud)
这是模板化谓词的优化步骤。
这并不是函子比函数更容易使用的问题。两者在 boost 和 STL 环境中的工作方式几乎相同。
它们的不同之处在于模板实例化。
想象一个需要谓词的简单模板函数
template< typename Predicate >
void DoSomething( Predicate func )
{
func();
}
Run Code Online (Sandbox Code Playgroud)
使用函数将使用函数指针实例化模板实例。
void changeString();
DoSomething( &changeString );
// This creates a template instantiation expecting a pointer to a function.
// The specific pointer may be evaluated at runtime.
// void DoSomething( void(func*)() );
Run Code Online (Sandbox Code Playgroud)
使用仿函数将实例化具有特定仿函数类型的模板实例。
struct changeString
{
void operator() ();
}
DoSomething( changeString() );
// This creates a template instantiation expecting an instance of the struct.
// The exact function being called is now known at compile time.
// void DoSomething( changeString );
Run Code Online (Sandbox Code Playgroud)
有了仿函数,现在可以很好地定义特定的功能,并且传入的结构可能不会被使用,并且可以被优化掉。