我希望能够为成员函数声明以及在其他地方使用的它们的指针使用单个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 = &B::foo;”之类的回避方式,因此,我希望尽可能减少接口协定。是否有用于命名非指针成员函数类型的有效语法? void(B::)(int)void(B::&)(int)等的普通变体不起作用。

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

最佳答案

您似乎在寻找的语法是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.

关于c++ - C++中的非指针成员函数typedef?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23346641/

10-12 20:39