简体   繁体   中英

C++ Passing a member function of a template class to another function

This works fine for a non-member function. How can I change it to be able to perform the same operation with a member function. I have tried the "function pointers" technique, and it was not efficient in terms of performance.

template <typename Func>
int f(int a, Func somefunc) {
  somefunc(a);
  return 0;
}
...
f(5,myfoo);

I want to be able to do this:

int myClass::mybar() {    
  f(5,myfoo); //where myfoo is actually "myClass::myfoo" here. 
              //I want myClass to be the template class. 
}

How can I define a template class and make its member-function template as well, such that f works with any class and any member-function?

Thanks!

Wait... Hammer Time

You mean do something like this??

#include <stdio.h>
#include <string>
#include <iostream>

void my_int_func(int x)
{
    printf( "%d\n", x );
}

void my_string_func(std::string x)
{
    std::cout << x << std::endl;
}

template <typename type, typename Func>
int f(type a, Func somefunc) {
  somefunc(a);
  return 0;
}

int main()
{
    void (*foo)(int);
    void (*bar)(std::string);
    /* the ampersand is actually optional */
    foo = &my_int_func;
    bar = &my_string_func;

    f(5, foo);
    f(std::string("thing"), bar);

    return 0;
}

OK, now comes the said truth: Member pointers are also pointers (OK, sometimes they are just offsets, and it can be even more compliated in case of multiple/virtual inheritance...). And now maybe a possible solution although I don't know what is your actual use case for passing a member function pointer to a template method of a template...

template <typename T>
class C
{
public:
    C()
    {
        f(5, &C::f);
    }

    template <typename Func>
    int f(int a, Func somefunc)
    {
        (this->*somefunc)(a);
        return 0;
    }
    void f(int i)
    {
        printf("%s(%d)\n", __FUNCTION__, i);
    }
    void g(int i)
    {
        printf("%s(%d)\n", __FUNCTION__, i);
    }
};

int main()
{
    C<int> c;
    c.f(6, &C<int>::g);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM