【发布时间】:2016-12-09 18:53:45
【问题描述】:
Stroustrup 给出了在变换操作期间使用重载的operator() 对向量元素执行函数的示例:
class Example
{
public:
std::vector<int> Test1 {1,2,3,4,5};
std::vector<int> Test2;
int operator()(int el);
void MyFunction();
}
int Example::operator()(int el)
{
return el + 1;
}
void Example::MyFunction()
{
std::transform(Test1.begin(), Test1.end(), std::back_inserter(Test2), std::bind(Example(), std::placeholders::_1))
}
但是,与 lambda 表达式相比,上面的代码看起来非常冗长:
std::transform(Test1.begin(), Test1.end(), std::back_inserter(Test2), [](int el){return el + 1;});
我是否正确地说使用重载的operator() 方法没有什么价值?或者在使用 STL 算法时,它们是否仍然有用?
【问题讨论】:
-
您的标题是通用的 - 运算符重载 - 但实际上您的意思是 operator() 重载,更准确地说,是使用函子。我将编辑问题。
-
为什么在第一个示例中使用
std::bind?