c++ - Passing template arguments as target type -
in shortened example (not real world code), i'm attempting call callback
int &
, however, when going via callmethod
method, template parameter interpreted int
, meaning can't convert target parameter type.
is possible? know can cast parameter correct type when calling callmethod
, i'd solution 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; }
you aren't correctly forwarding arguments. in order make use of perfect-forwarding std::forward
should operate on forwarding references, when have rvalue reference in deduced context. callmethod
function should this:
template <typename method, typename ...params> void callmethod(method method, params&& ...params) { method(std::forward<params>(params)...); }
Comments
Post a Comment