Dec 8, 2011 at 1:32pm UTC
Just out of curiosity, is it possible to initialize a temporary function pointer and call it in one go?
void (*)(int , short )(&SomeFunc)(3, 2);
Or would I have to use a typedef?
1 2
typedef void (*visf)(int , short );
visf(&SomeFunc)(3, 2);
Obviously it has no practical use except having a lot of parenthesis in one expression...
I'm basing the idea off the fact that you can construct other temporary objects:
std::cout << std::string("text" ).length() << std::endl;
Last edited on Dec 8, 2011 at 1:34pm UTC
Dec 8, 2011 at 1:43pm UTC
I would say no. See if you can make sense out of it: What is the data type of SomeFunc? Probably it is a function that matches exactly the type of function pointer you are declaring, and therefore, what is the point anyway since you can call it directly like this SomeFunc(3, 2);
?
Now let's imagine SomeFunc is a variable of type void*. Maybe here you can typecast without declaring the typedef. But I think it is as far as you can go.
Last edited on Dec 8, 2011 at 1:43pm UTC
Dec 8, 2011 at 2:41pm UTC
Sure you can, you forgot some parentheses though
Typedef version
1 2 3 4 5 6 7 8 9 10
#include <iostream>
void SomeFunc(int n1, short n2)
{
std::cout << n1 << ' ' << n2 << '\n' ;
}
int main()
{
typedef void (*visf)(int , short );
(visf(SomeFunc))(3, 2);
}
demo:
http://ideone.com/6YVvv
one-liner version
1 2 3 4 5 6 7 8 9
#include <iostream>
void SomeFunc(int n1, short n2)
{
std::cout << n1 << ' ' << n2 << '\n' ;
}
int main()
{
((void (*)(int ,short ))(SomeFunc))(3,2);
}
demo:
http://ideone.com/VmmaN
Although it's obviously redundant, you don't need a type to make a function pointer:
(&SomeFunc)(3,2);
or even
(+SomeFunc)(3,2);
To make a better analogy with std::string("text"), try std::function:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <functional>
void SomeFunc(int n1, short n2)
{
std::cout << n1 << ' ' << n2 << '\n' ;
}
int main()
{
(std::function<void (int ,short )>(SomeFunc))(3,2);
}
demo:
http://ideone.com/v9OOZ
Last edited on Dec 8, 2011 at 2:45pm UTC