【发布时间】: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 = &B::foo;”这样的回避,所以如果可能的话,我想尽量减少我的接口契约。是否有命名非指针成员函数类型的有效语法? void(B::)(int)、void(B::&)(int) 等的简单变体都不起作用。
编辑:接受的答案 - func_type Class::* 语法是我所缺少的。谢谢各位!
【问题讨论】:
-
对于任何类型
T和类类型C,指向成员的指针类型是T C::*。 IE。using vi_pm_ft = vi_ft B::*;. -
那么
B::vi_ft B::*h{&B::baz};有效吗?谢谢!
标签: c++ typedef member-function-pointers