【问题标题】:Non-pointer member function typedefs in C++?C ++中的非指针成员函数typedef?
【发布时间】:2014-04-28 16:43:29
【问题描述】:

我希望能够对成员函数声明和在其他地方使用的指向它们的指针使用单个 C++ typedef。如果我能像下面这样匹配非成员函数的结构,那就完美了:

#include <iostream>

using x_ft = char (int);

// Forward decls both advertise and enforce shared interface.
x_ft foo, bar;

char foo(int n) { return (n % 3 == 0) ? 'a' : 'b'; }
char bar(int n) { return (n % 5 == 0) ? 'c' : 'd'; }

int main(int argc, char *argv[]) {
  // Using same typedef for pointers as the non-pointers above.
  x_ft *f{foo};
  x_ft *const g{(argc % 2 == 0) ? bar : foo};

  std::cout << f(argc) << ", " << g(argc * 7) << std::endl;
}

我似乎无法避免非静态成员函数的类型准重复:

struct B {
  // The following works OK, despite vi_f not being class-member-specific.
  using vi_ft = void(int);
  vi_ft baz, qux;

  // I don't want redundant definitions like these if possible.
  using vi_pm_ft = void(B::*)(int); // 'decltype(&B::baz)' no better IMO.
};
void B::baz(int n) { /* ... */ }
void B::qux(int n) { /* ... */ }

void fred(bool x) {
  B b;
  B::vi_pm_ft f{&B::baz}; // A somehow modified B::vi_f would be preferable.

  // SYNTAX FROM ACCEPTED ANSWER:
  B::vi_ft B::*g{x ? &B::baz : &B::qux};   // vi_ft not needed in B:: now.
  B::vi_ft B::*h{&B::baz}, B::*i{&B::qux};

  (b.*f)(0);
  (b.*g)(1);
  (b.*h)(2);
  (b.*i)(3);
}

我的实际代码不能真正在任何地方使用像“auto f = &amp;B::foo;”这样的回避,所以如果可能的话,我想尽量减少我的接口契约。是否有命名非指针成员函数类型的有效语法? void(B::)(int)void(B::&amp;)(int) 等的简单变体都不起作用。

编辑:接受的答案 - func_type Class::* 语法是我所缺少的。谢谢各位!

【问题讨论】:

  • 对于任何类型T和类类型C,指向成员的指针类型是T C::*。 IE。 using vi_pm_ft = vi_ft B::*;.
  • 那么B::vi_ft B::*h{&amp;B::baz}; 有效吗?谢谢!

标签: c++ typedef member-function-pointers


【解决方案1】:

您似乎正在寻找的语法是vi_ft B::*f

using vi_ft = void(int);

class B {
public:
    vi_ft baz, qux;
};
void B::baz(int) {}
void B::qux(int) {}

void fred(bool x) {
    B b;
    vi_ft B::*f{ x ? &B::baz : &B::qux };
    (b.*f)(0);
}

int main() {
    fred(true);
    fred(false);
}

Above code at coliru.

【讨论】:

  • 是的,完美。 Kerrek 领先你几分钟,但你有一个完整的答案,我可以接受。谢谢你们!
猜你喜欢
  • 2011-03-04
  • 2010-11-02
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
相关资源
最近更新 更多