4

在 C++11 中是否有一种简单的方法可以做到这一点?如果可能的话,我想保留多重继承和循环遍历包中所有静态函数的能力。

#include <cstdio>

struct A { static void foo() {printf("fA\n");} static void bar() {printf("bA\n");} };
struct B { static void foo() {printf("fB\n");} static void bar() {printf("bB\n");} };
struct C { static void foo() {printf("fC\n");} static void bar() {printf("bC\n");} };

template <typename... T>
struct Z : public T... {
    static void callFoos() {
        /* ???? WHAT'S THE SYNTAX 
             T...::foo();
             T::foo()...;
        */
    }

    static void callBars() {
        /* ???? WHAT'S THE SYNTAX 
             T...::bar();
             T::bar()...;
        */
    }

};

int main() {
    Z<A, B, C>::callFoos();
    Z<A, B>::callBars();
}
4

2 回答 2

5

添加一组调度程序函数重载:

void foo_caller() { }

template <typename T, typename ...Args>
void foo_caller()
{
    T::foo();
    foo_caller<Args...>();
}

然后在里面使用callFoos()

foo_caller<T...>();
于 2013-05-01T19:39:48.980 回答
4

包扩展需要一个解包上下文,数组构造就是其中之一。没有递归:

static void callFoos() {
  int unused[] = {(T::foo(), 0)...};
  (void)unused; // suppress warnings
}

callBars.

于 2013-05-01T22:00:53.997 回答