---- Problem Summary ----
I'm attempting to create a callable function pointer inside of a function using templates for its return value and its arguments using C++ 14. I want the callable function pointer to return the templated type, and accept templated arguments. However, I also want the callable function pointer to point to an existing function at the address provided in an argument as an integer. This I am unsure of how to do. Below is an illustration of my current incomplete code:
1 2 3 4 5 6 7
|
template <class retTempl, class argTempl_1, class argTempl_2>
retTempl TEST_1(argTempl_1 value1, argTempl_2 value2, int addr) {
typedef retTempl(*TEST_2)(argTempl_1, argTempl_2);
return TEST_2(value1, value2);
}
| |
In this case, "TEST_2" is the new function pointer that I want to call, and the "addr" argument is the address of an existing function that I want the "TEST_2" pointer to point to.
The current error that the VS 2019 compiler throws at me is the following:
|
Error C2440 '<function-style-cast>': cannot convert from 'initializer list' to 'operationFunction'
| |
I am unsure of exactly what it's trying to tell me, researching this error online leads to several possible causes, not all of which necessarily have to do with function pointers. However, this error may not even be relevant, as I have not been able to implement the function address yet. That is mostly what I want to focus on here.
---- My Attempts ----
I know that in order to make a function pointer created with the typedef keyword point to an actual function, you need to set the pointer variable equal to whichever function you want the pointer to point to. So for instance (example from
https://www.section.io/engineering-education/function-pointers-in-c++/):
1 2 3 4 5 6 7 8 9 10 11
|
int add(int x ,int y)
{
return x + y;
}
int main()
{
int (*funcptr)(int, int);
funcpointr = add;
...
}
| |
However, here the function that I want the "TEST_2" pointer to point to is different every time that "TEST_1" is called, with a different return value and arguments. Therefore, I cannot simply set the "TEST_2" variable equal to the "addr" argument:
1 2 3 4 5 6 7 8
|
template <class retTempl, class argTempl_1, class argTempl_2>
retTempl TEST_1(argTempl_1 value1, argTempl_2 value2, int addr) {
typedef retTempl(*TEST_2)(argTempl_1, argTempl_2);
TEST_2 = addr;
return TEST_2(value1, value2);
}
| |
as this now supplies me with an additional VS error:
|
Error C2513 'retTempl (__cdecl *)(argTempl_1,argTempl_2)': no variable declared before '='
| |
I would assume that I would require another pointer variable here, perhaps from a list of function pointers that I want the "TEST_2" variable to point to, but at this point I would like to hear a second opinion before I resume.
Is what I'm trying to achieve here even possible to do with C++? Is there a different way that this should be done that I'm not aware of?
Thank you in advance for reading my post, any guidance is appreciated!