繁体   English   中英

C ++中的非指针成员函数typedef?

[英]Non-pointer member function typedefs in C++?

我希望能够为成员函数声明和其他地方使用的指针使用单个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; ”这样的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);
}

以上代码在coliru。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM