c++ - 如何让 C++ 模板类调用另一个类的方法?

标签 c++ templates pointer-to-member

我有类 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% 满足我的需求。如何重写上述代码以便:

  1. 方法 bar 是类的公共(public)成员,而不是独立的 功能
  2. 参数 df 被传递给方法 barpublicbar 所属类的成员, 允许 barvoid (void)
  3. 类型
  4. 对象类型 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/

相关文章:

c++ - 使用模板模板参数打破模板循环依赖

android - 蓝牙串口通讯,HC-06模块转安卓手机

c++ - 连接到 postgresql 数据库的奇怪错误

c++ - 正确处理listview中可编辑子项的子项编辑(或取消子项编辑)

c++ - 模板定义中的模板特化 : is this supported for all compilers or standard usage?

c++ - 成员函数实例化

c++ - 你如何初始化私有(private)成员函数指针的静态映射?

c++ - 抽象指向成员函数的指针 : safety and alternatives

c++ - 我可以安全地将指向 const 成员的指针转换为相同类型但非常量吗?

c++ - OPENSSL 错误 : lib(6) func(101) reason(100) evp_enc. c