C++ 将模板类的成员函数传递给另一个函数

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

本文关键字:函数 另一个 成员 C++      更新时间:2023-10-16

这对于非成员函数来说工作得很好。如何更改它以便能够使用成员函数执行相同的操作。我尝试过"函数指针"技术,它在性能方面效率不高。

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

我希望能够做到这一点:

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

如何定义模板类并使其成员函数模板,以便f适用于任何类和任何成员函数?

谢谢!

等等...锤击时间

你的意思是做这样的事情??

#include <stdio.h>
#include <string>
#include <iostream>
void my_int_func(int x)
{
printf( "%dn", 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;
}

好的,现在说的真相是:成员指针也是指针(好吧,有时它们只是偏移量,在多重/虚拟继承的情况下可以更符合......现在也许是一个可能的解决方案,尽管我不知道您将成员函数指针传递给模板的模板方法的实际用例是什么......

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;
}