I have the following code that works as expected:
#include <iostream> using namespace std; typedef int (TMyFunc)(int); TMyFunc* p; int x(int y) { return y*2; } int main() { p = &x; cout << (*p)(5) << endl; }
What I want to do is skip the definition of x and define p there directly. Sort of
TMyFunc p; p(y){return y*2;} TMyFunc p; p(y){return y*2;} .
Is it possible? If so, how do I do this? If not?
EDIT:
After looking at the answers, I think I should clarify: I want the definition to be separate. that is, the definition of the function will be in a common object. The application will receive a function pointer through dlsym . I do not want a function object. I want to know if I can define a function using its type, which will contain a header file that is common to both a common object and an application. Hope this worked out right :).
EDIT2: for sbi :)
This is in the header, which is included both in the application and in the shared object:
#define FNAME_GET_FACTORY "GetFactory" #define FNAME_GET_FUNCTION_IDS "GetFunctionIDs" #define FNAME_GET_PLUGIN_INFO "GetPluginInfo" typedef FunctionFactory* (*TpfGetFactory)(); typedef size_t (*TpfGetFunctionIDs)(int**); typedef PluginInfo* (*TpfGetPluginInfo)();
Something like this happens in the application:
TpfGetFactory pF = (TpfGetFactory)dlsym(pHandle, FNAME_GET_FACTORY); //Use pF for anything
Now for this I have to define GetFactory as follows in a generic object:
extern "C" FunctionFactory* FNAME_GET_FACTORY(){
Forget the extern "C" for now. Can I define this function using the already installed TpfGetFactory type? (This is not a huge problem that I know, but I'm curious if this is possible :)). I want something like this in a shared object:
TpfGetFactory f; f(){
EDIT3:
My attempt:
#include <iostream> using namespace std; typedef int (TF)(int); TF f; f(int x) { return x*2; } int main() { x(3); } main.cpp:9: error: ISO C++ forbids declaration of Γ’β¬ΛfΓ’β¬β’ with no type main.cpp: In function Γ’β¬Λint main()Γ’β¬β’: main.cpp:16: error: Γ’β¬ΛxΓ’β¬β’ was not declared in this scope