Passing Template Arguments as Target Type

In this shorthand example (not in the real world) I am trying to call Callback

with int &

, however when stepping through the method, CallMethod

the template parameter is interpreted as int

, which means it cannot convert it to the target type of the parameter.

Is it possible? I know that when called, CallMethod

I can cast the parameter to the correct type, however, I would like the solution to be implicit if possible.

#include <functional>
#include <iostream>

using namespace std;

void Callback(int &value)
{
    value = 42;
}

template <typename Method, typename ...Params>
void CallMethod(Method method, Params ...params)
{
    method(std::forward<Params>(params)...);
}

int main()
{
    int value = 0;
    CallMethod(&Callback, value);

    cout << "Value: " << value << endl;

    return 0;
}

      

+3


source to share


1 answer


You are redirecting your arguments incorrectly. To use flawless redirects std::forward

, you need to work with the redirects that are there when you have an rvalue reference in the inferred context. Your function CallMethod

should look like this:

template <typename Method, typename ...Params>
void CallMethod(Method method, Params&& ...params)
{
    method(std::forward<Params>(params)...);
}

      



Demo

+6


source







All Articles