C ++ Template Variadic - 为每个模板参数调用一次成员函数

问题描述 投票:-1回答:1

我有一个EntityComponent-System,并且有一个组件应该调用各种其他组件上的函数。对于这个例子,我选择了一个布尔函数结果的简单组合。

ResultCombinerComponent具有可变参数模板参数,对于每个参数,它应按照给定模板参数的顺序调用函数。订单非常重要。

然后组合函数调用的结果。

在下面的代码中,我刚刚用psuedo-C ++替换了我不知道如何实现的部分

template<typename... Args>
class ResultCombinerComponent
{
    template<typename T> 
    bool calcSingleResult()
    {
        return getComponent<T>()->calcResult();
    }

    bool calcResult()
    {
        bool result = true;
        for (int i = 0; i < sizeof...(Args); i++)  // doesn't work
        {
            if (!calcSingleResult<Args(i)>()  // doesn't work
            {
                result = false;
                break;
            }
        }
        return result;
    }

}


class A
{ 
    bool calcResult();
}
class B
{ 
    bool calcResult();
}
class C
{ 
    bool calcResult();
}
c++ templates c++11 variadic-templates
1个回答
2
投票

在C ++ 17中,您可以这样做:

bool calcResult()
{
    return (calcSingleResult<Args>() && ...);
}

在c ++ 11中,您必须有其他方法:

template <typename T>
bool calcImpl()
{
    return calcSingleResult<T>();
}

template <typename T, typename T2, typename...Ts>
bool calcImpl()
{
    return calcSingleResult<T>() && calcImpl<T2, Ts...>();
}

bool calcResult()
{
    return calcImpl<Args...>();
}
© www.soinside.com 2019 - 2024. All rights reserved.