I'm been grinding my head against an idea that is simple enough in my head, but I can't figure out how to implement in C++.
Normally, I can declare a class with a conversion operator like in this simple example:
class Foo
{
private:
int _i;
public:
Foo( int i ) : _i(i) { }
operator int( ) const
{
return i;
}
};
So now I can write awesome stuff like
int i = Foo(3);
But in my particular case, I would like to provide an operator for converting an object to a function pointer (e.g. converting a Bar
instance to a int(*)(int, int)
function pointer). Here's what I initially tried:
class Bar
{
private:
int (*_funcPtr)(int, int);
public:
Bar( int (*funcPtr)(int, int) ) : _funcPtr(funcPtr) { }
operator int(*)(int, int) ( ) const
{
return _funcPtr;
}
};
But the operator function fails to compile, with these errors being generated:
expected identifier before '*' token
'<invalid-operator>' declared as a function returning a function
I have also tried simple variations on the above, such as surrounding the return type in parenthesis, but all these ideas have also failed.
Does anyone know what the syntax is for declaring a conversion-to-function-pointer operator method, or whether it is even possible to do so?
Note: I am compiling this with Code::Blocks using GCC 4.5.2. Answers involving some of the new C++0x concepts are also welcome.
Edit
In my strive for simplifying the example, I unintentionally left out one detail. It's a bit weird, but rather than strictly returning an int(*)(int,int)
pointer, the conversion operator is intended to be templated:
template<typename ReturnType, typename ArgType1, typename ArgType2>
operator ReturnType(*)(ArgType1, ArgType2) ( ) const
{
// implementation is unimportant here
}
As far as I know, I no longer cannot typedef such a type. This clearly makes things much more clumsy, but I hope that there is still a way.