我有类 A 需要调用模板类 B 的成员函数。四处搜索我在这个网站上找到了这个示例代码:
#include <iostream>
template<typename T, typename FType>
void bar(T& d, FType f) {
(d.*f)(); // call member function
}
struct foible
{
void say()
{
std::cout << "foible::say" << std::endl;
}
};
int main(void)
{
foible f;
bar(f, &foible::say); // types will be deduced automagically...
}
来自这个答案: C++ method name as template parameter
但它并没有 100% 满足我的需求。如何重写上述代码以便:
- 方法
bar
是类的公共(public)成员,而不是独立的 功能 - 参数
d
和f
被传递给方法bar
是public
是bar
所属类的成员, 允许bar
为void (void)
类型
- 对象类型
foible
是类而不是结构(可选)?
[编辑 1] 我自己的重写尝试符合第 1) 和 2) 点,但错误的是:
#include <iostream>
template<class T, void (T::*FType)()>
class foo {
public:
T obj;
FType f;
void bar(void) {
(obj.*f)(); // call member function
} // end bar
}; // end class foo
struct foible
{
void say()
{
std::cout << "foible::say" << std::endl;
}
};
int main(void)
{
foible f;
foo<foible, void (foible::*)()> c;
c.T = f;
c.Ftype = &foible::say;
c.bar(); // types will be deduced automagically...
}
我的目标是让类类型为“A”的对象调用类类型为“B”的对象的方法,以便在这些方法执行时类型为“B”的对象可以使用其“this”指针来引用它的本地数据。我想在类类型“A”中使用函数指针,这样只需指定一次,而且我不希望一个类必须从另一个类派生。
最佳答案
你把事情搞得太复杂了。忘掉指向方法的指针。目前没有理由使用它们。
只需做这样的事情:
template<typename F>
void bar(F f) {
doSomething();
f(someArg);
doSomething();
}
int main(void)
{
foible f;
bar([&f](auto x) { f.someMagicMethod(x); } );
return 0;
}
请注意,与使用方法指针相比,这种方法更加灵活和可读。
关于c++ - 如何让 C++ 模板类调用另一个类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791544/