Passing member function templates as arguments
Can I pass a member function template as an argument to another function? How would I do that?
Yes, you can pass member function templates as arguments to other functions, but the syntax is a bit tricky. You need to use a template parameter for the class, and then a pointer-to-member syntax to pass the function.
Here's an example:
#include <iostream>
template <typename T, typename MemberFn,
typename... Args>
void CallMemberFn(T& obj, MemberFn fn,
Args&&... args) {
(obj.*fn)(std::forward<Args>(args)...);
}
class Test {
public:
template <typename T>
void MemberFnTemplate(T x) {
std::cout << "In MemberFnTemplate "
<< x << std::endl;
}
};
int main() {
Test t;
CallMemberFn(t,
&Test::template MemberFnTemplate<int>, 42);
}
In MemberFnTemplate 42
In CallMemberFn
, T
is the class type, MemberFn
is a pointer-to-member function type, and Args...
is a parameter pack representing the types of the arguments to be passed to the member function.
When calling CallMemberFn
, we pass three things:
- An instance of the
Test
class (t
). - A pointer to the specific instantiation of the member function template we want (
&Test::template MemberFnTemplate<int>
). Note the use of thetemplate
keyword here, which is necessary when passing a member function template as a template argument. - The actual arguments to be passed to the member function (
42
in this case).
Inside CallMemberFn
, we unpack the args...
parameter pack and forward each argument to the member function using std::forward
.
This updated version of CallMemberFn
is more flexible, as it can handle member function templates that take any number of arguments.
However, it's worth noting that passing member function templates as arguments is still a complex operation with tricky syntax. In many cases, you might find it simpler and more readable to use regular function templates or lambda expressions instead of member function templates if you need to pass them as arguments to other functions.
Member Function Templates
Learn how to create and use member function templates in classes and structs, including syntax, instantiation, and advanced techniques