及其简化:
bool
,具有相同的基类,不带参数)答案 0 :(得分:2)
template<class T, class...Ms>
void run_all(T* t, Ms&&... ms) {
using discard=int[];
(void)discard{0,(void(
(t->*ms)()
),0)...};
}
使用:
struct foo {
bool t1() { return true; }
bool t2() const { return false; }
};
int main() {
foo f;
run_all(&f, &foo::t1, &foo::t2);
}
run_all
是迟钝的,但那是因为我们没有C ++ 17。
template<class T, class...Ms>
void run_all(T* t, Ms&&... ms) {
((void)((t->*ms)()),...);
}
这有点简单,甚至:
template<class T, class...Ms>
void run_all(T* t, Ms&&... ms) {
((t->*ms)(),...);
}
依赖于t->*ms
返回一个理智的类型。
我们还可以依赖ms
返回bool并执行:
template<class T, class...Ms>
void run_all(T* t, Ms&&... ms) {
(void)std::initializer_list<bool>{(t->*ms)()...};
}
或
template<class T, class...Ms>
void run_all(T* t, Ms&&... ms) {
using discard=bool[];
(void)discard{false,(t->*ms)()...};
}
请注意,所有这些都按顺序执行方法并支持传递0方法。
上述某些void
强制转型用于阻止未使用值的警告。
其他人可以处理调用返回超载operator,
的类型的可能性。
答案 1 :(得分:1)
class MyClass {
/* The methods to be executed: */
bool func_1() const { /* ... */ }
bool func_2() const { /* ... */ }
// ...
/* The parameter pack expansion: */
typedef bool (MyClass::*FuncPtr)() const;
template<class T = void>
void Expand() const {} // Termination version.
template<FuncPtr ptr, FuncPtr ... Args>
void Expand() const {
(this->*ptr)();
Expand<Args...>();
}
/* The function that calls them all: */
void RunAll() const {
Expand<
&MyClass::func_1, // <-- input to parameter pack
&MyClass::func_2
>();
}
};
没有递归的替代版本:
class MyClass {
/* The methods to be executed: */
bool func_1() const { /* ... */ }
bool func_2() const { /* ... */ }
// ...
/* The parameter pack expansion: */
typedef bool (MyClass::*FuncPtr)() const;
template<typename ... T> void ignore(T && ...) {}
template<FuncPtr ... Args>
void Expand() const {
ignore( ((this->*Args)(),0) ... );
}
/* The function that calls them all: */
void RunAll() const {
Expand<
&MyClass::func_1, // <-- input to parameter pack
&MyClass::func_2
>();
}
};
(来自@Yakk的贡献)