Re: int (*&)()
Asif Zaidi wrote:
On Feb 8, 7:12 am, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Asif Zaidi wrote:
On Feb 8, 12:28 am, Syron <mr.sy...@googlemail.com> wrote:
Am 08.02.2010 04:45, schrieb Asif Zaidi:
What does the syntax in subject line mean - how should I read it.
Thanks
Asif
if this is a typedef (like 'int(*&func)()') it is a reference to a
pointer to a function that returns an int.
Kind regards, Syron
I am trying to implement the following and getting compile failure.
Any suggestions ?
typedef int (*& func_ptr1)();
int goo()
{
cout << "un goo" << endl;
return 0;
}
int main()
{
func_ptr1 p1 = goo;
}
The error is below
1>d:\profiles\waz003\my documents\visual studio 2008\projects
\hw5_3\hw5_3\hw5_3.cpp(174) : error C2440: 'initializing' : cannot
convert from 'int (__cdecl *)(void)' to 'func_ptr1'
I believe the reference to non-const requires a modifiable l-value for
initialisation. Your 'goo' is not an lvalue. You can either do
typedef int (* const & func_ptr_ref)();
...
func_ptr_ref pr = goo;
or define a variable of the type 'pointer to function' and initialise
your reference with it:
...
int main()
{
int (*some_fptr)();
func_ptr1 p1 = some_fptr;
}
V
[..]
Please do not quote signatures.
Thanks Victor - a few questions though
The first option you state: why does it work. I had the same thing you
had except I did NOT have the const in the typedef definition. Why
would the const help ?
A reference to const can be initialised with a non-lvalue. That's just
one of the language rules.
The second option you state: that is just a function ptr is it not. It
is not a reference to a ptr to a function which is what I want ?
Not sure I understand your question. 'p1' is your reference to a
pointer to function. Assign something to 'p1' and you're going to be
changing 'some_ptr'.
Now, take the "function" out of all this, perhaps it's what confuses
you, and imagine that you have just ints. Now, 12345 is an int, isn't
it? Can you define a reference to an int and initialize it with 12345?
No, you're not allowed to, because 12345 is not an lvalue.
int &ri = 12345;
However, you can define a reference to a const int and initialise it
with that number:
int const & rci = 12345;
(the compiler will create a temporary with that value and make the
temporary live as long as the reference to it).
Or you could have a real int (a variable) and initialise a reference
with it:
int real_int;
int& ri = real_int;
I am not sure this is any clearer, but the principles that govern the
initialisation of references to objects do apply when those objects are
pointers to functions.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask