C++模板Variadic-为每个模板参数调用一个成员函数
C++ Template Variadic - Call a member function once for every template argument
我有一个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...>();
}
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针