我一直在反对一个简单易懂的想法,但我无法弄清楚如何用C++实现.
通常,我可以使用转换运算符声明一个类,如下例所示:
class Foo
{
private:
int _i;
public:
Foo( int i ) : _i(i) { }
operator int( ) const
{
return i;
}
};
Run Code Online (Sandbox Code Playgroud)
所以现在我可以写出很棒的东西了
int i = Foo(3);
Run Code Online (Sandbox Code Playgroud)
但在我的特定情况下,我想提供一个操作符,用于将对象转换为函数指针(例如,将Bar实例转换为int(*)(int, int)函数指针).这是我最初尝试的内容:
class Bar
{
private:
int (*_funcPtr)(int, int);
public:
Bar( int (*funcPtr)(int, int) ) : _funcPtr(funcPtr) { }
operator int(*)(int, int) ( ) const
{
return _funcPtr;
}
};
Run Code Online (Sandbox Code Playgroud)
但是运算符函数无法编译,生成这些错误:
expected identifier before '*' token
'<invalid-operator>' declared as a function returning a function
Run Code Online (Sandbox Code Playgroud)
我也尝试过上面的简单变体,比如在括号中包含返回类型,但所有这些想法也都失败了. …
您能否以简单,优雅和智能的方式介绍如何在没有特殊库的情况下在C++ 03中实现基本的lambda表达式?他们应该可以做这样的事情:
for_each(some_vector.begin(), some_vector.end(), _first = -5)
sort(some_vector.begin(), some_vector.end(), _first > _last)
Run Code Online (Sandbox Code Playgroud)
我在StackOverflow和互联网的其他地方看过很多主题,但不幸的是,我没有找到有用的东西.另一个想法是仔细研究Boost实现,但遗憾的是,我的水平现在还不太合适.
先感谢您!