【问题标题】:Method function pointer template without naming class type没有命名类类型的方法函数指针模板
【发布时间】:2017-11-01 16:27:49
【问题描述】:

考虑这个template函数,调用class T对象的方法。

template<class T, void (T::*Method)()>
void circuitousInvoke(T* callee) {
    (callee->*Method)();
}

例子:

struct A {
    void test() {};
}

circuitousInvoke<A, &A::test>(new A);

由于类型 T 已经被参数 callee 知道,所以有没有办法避免键入这种类型?

circuitousInvoke<&A::test>(new A);

编辑

这个问题只涉及模板函数。在这种情况下,继承和其他基于类的解决方案不适合。 (在我的项目中,使用包装对象比输入额外的名称更糟糕。)

【问题讨论】:

标签: c++ templates member-function-pointers syntactic-sugar


【解决方案1】:

在 C++17 中使用 auto 是可能的

template<auto Method, typename T>
void circuitousInvoke(T* callee) {
    (callee->*Method)();
}

然后

A a;
circuitousInvoke<&A::test>(&a);

【讨论】:

  • gcc 已经支持-std=C++17(具有该功能),clang 支持-std=c++1z
猜你喜欢
  • 2018-12-04
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 2015-04-04
  • 1970-01-01
  • 2021-06-22
  • 2014-01-17
  • 1970-01-01
相关资源
最近更新 更多