Let's assume I have the structure X
declared and defined like this:
struct X {
int i;
X(int i = 0) : i(i) { std::cout << "X(int i = " << i << "): X[" << this << "]" << std::endl; }
int multiply(int a, int b = 1) { return i * a * b; }
};
I want to call X::multiply
via function-pointer. To do this, I defined a proxy
-function:
template <typename ObjectType,
typename ReturnType,
typename... ParameterTypes>
ReturnType proxy(ObjectType * object,
ReturnType (ObjectType::* func)(ParameterTypes...),
ParameterTypes... params) {
return (object->*func)(params...);
}
I use it like this:
int main() {
X x(10);
int a = 5;
int r = proxy<X, int, int, int>(&x, &X::multiply, a, 2); // proxy<...> works
//int r = proxy(&x, &X::multiply, a, 2); // proxy works
//int r = proxy2<X, int, int, int, int>(&x, &X::multiply, a, 2); // proxy2<...> does not work
//int r = proxy2(&x, &X::multiply, a, 2); // proxy2 works
std::cout << "Proxy-Test:"
<< "\na = " << 5
<< "\nr = " << r
<< std::endl;
}
proxy<...>
and even proxy
work like a charm, except that I cannot call proxy
with only one argument although the second one should be optional. (Leaving out the right-value-argument 2 in proxy
's invocation will yield an error.) Of course, proxy
is expecting exactly two arguments, so I also created another version of the proxy
-function:
template <typename ObjectType,
typename ReturnType,
typename... ParameterTypes,
typename... ArgumentTypes>
ReturnType proxy4(ObjectType * object,
ReturnType (ObjectType::* func)(ParameterTypes...),
ArgumentTypes... args) {
return (object->*func)(args...);
}
This version has its types for parameters and arguments split into separate parameter-packs. Weirdly enough, invoking proxy2<X, int, int, int, int>(&x, &X::multiply, a, 2);
makes the compiler think this invocation's ParameterTypes are (int, int, int) while ArgumentTypes are (int, int).
Equally weird is that the invocation proxy2(&x, &X::multiply, a, 2);
works just fine.
None of those work if I leave out the right-value 2.
The problem remains: How can I call X::multiply
with only the a-parameter, therefore without specifying b?