gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:54:06 25 4
gpt4 key购买 nike

这适用于非成员函数。我如何更改它才能使用成员函数执行相同的操作。我已经尝试过“函数指针”技术,但它在性能方面并不高效。

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( "%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;
}

关于C++ 将模板类的成员函数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com