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

C++ Template Variadic - Call a member function once for every template argument

本文关键字:一个 函数 成员 调用 Variadic- 模板 C++ 参数      更新时间:2023-10-16

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

ResultCombinaterComponent具有可变的模板参数,对于这些参数中的每一个,它都应该按照给定模板参数的顺序调用一个函数。秩序非常重要。

然后,函数调用的结果被组合在一起。

在下面的代码中,我只是替换了我不知道如何使用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++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...>();
}