I'm trying to pass an overloaded function pointer as shown below in the sample code.
class Sample
{
uint32_t method(char* input1, double input2);
uint32_t method(double input1);
}
template<class T, class... Args)
void processInput(T &&t, Args&&... a)
{
std::packaged_task<uint32_t(Args...)> task(std::bind(t, a...));
// other processing
}
// Caller invokes the below API
Sample* obj = new Sample();
processInput(static_cast<uint32_t(*)(double)>(&Sample::method), &*obj, 2.0f);
But this code doesn't compile. It keeps complaining that it can't determine which instance of overloaded function is intended. I referred several examples:
C++ overloaded method pointer
http://en.cppreference.com/w/cpp/language/static_cast
Can somebody help in pointing out what is going wrong here?
Once you fix the typos, the main problem is that you're trying to cast a member function pointer to a function pointer.
That is, the following is illegal:
static_cast<uint32_t(*)(double)>(&Sample::method)
error: invalid static_cast from type ‘uint32_t (Sample::*)(double) {aka unsigned int (Sample::*)(double)}’ to type ‘uint32_t (*)(double) {aka unsigned int (*)(double)}’
The syntax for a member function pointer is
ReturnT(ClassT::*)(ArgTs);
So your cast would have to be:
static_cast<uint32_t(Sample::*)(double)>(&Sample::method)
Example:
#include <iostream>
#include <functional>
struct Sample
{
uint32_t method(char* input1, double input2) { return 0; }
uint32_t method(double input1) { return 0; }
};
template<class T, class... Args>
void processInput(T &&t, Args&&... a)
{
auto task = std::bind(t, a...);
(void)task;
}
int main()
{
Sample* obj = new Sample();
processInput(static_cast<uint32_t(Sample::*)(double)>(&Sample::method), obj, 2.0f);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With