我希望能够为成员函数声明和其他地方使用的指针使用单个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);
}
我的实际代码无法真正使用&#34; auto f = &B::foo;
&#34;无处不在,所以如果可能的话,我想尽量减少我的界面合同。是否有一个有效的语法来命名非指针成员函数类型?没有void(B::)(int)
,void(B::&)(int)
等的微不足道的变体。
编辑:接受的答案 - func_type Class::*
语法是我所缺少的。谢谢,伙计们!
答案 0 :(得分:2)
您似乎正在寻找的语法是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);
}