C++ 将模板类的成员函数传递给另一个函数
C++ Passing a member function of a template class to another function
这对于非成员函数来说工作得很好。如何更改它以便能够使用成员函数执行相同的操作。我尝试过"函数指针"技术,它在性能方面效率不高。
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;
}
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何在qt中从另一个类调用函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 将 N-arg 函数包装到另一个函数中
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C++从另一个函数退出函数
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 在一个类中使用另一个类中的函数,而不在 c++ 中使用继承
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?