我一直在反对一个简单易懂的想法,但我无法弄清楚如何用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)
我也尝试过上面的简单变体,比如在括号中包含返回类型,但所有这些想法也都失败了. …