c – 迭代可变参数模板类的基类

前端之家收集整理的这篇文章主要介绍了c – 迭代可变参数模板类的基类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何迭代可变参数模板类的所有基类并为每个类调用一个函数.

这是一个最小的例子:

struct A { void foo() { std::cout << "A" << std::endl; } };
struct B { void foo() { std::cout << "B" << std::endl; } };
struct C { void foo() { std::cout << "C" << std::endl; } };

template<typename... U>
struct X : public U...
{
    void foo() {
        static_cast<U*>(this)->foo()...; // ??? should call `foo` for all `U`
    }
};

int main() {
    X<A,B,C> x;
    x.foo();
}

解决方法

这是一种方式:
struct thru{template<typename... A> thru(A&&...) {}};

struct A { void foo() { std::cout << "A" << std::endl; } };
struct B { void foo() { std::cout << "B" << std::endl; } };
struct C { void foo() { std::cout << "C" << std::endl; } };

template<typename... U>
struct X : public U...
{
    void foo() { thru{(U::foo(),0)...}; }
};

但是如果你关心电话的顺序,请注意here讨论的已知gcc错误.

原文链接:https://www.f2er.com/c/116372.html

猜你在找的C&C++相关文章