如何仅在语句匹配时才发送参数到函数?
How to send parameter to function only if statement is matched?
我有一个映射,我只想在函数中有元素时才发送给它。该函数需要一个参数包,因此我可以发送我想要的元素数量或数量。
有没有办法在调用本身中对地图进行大小检查?有很多地图将在同一调用中发送,这意味着在调用本身之外进行检查将非常繁琐。
我想要的伪代码:
std::map<int, int> a;
std::map<int, int> b;
std::map<int, int> c;
std::map<int, int> d;
fun( (if (a.size() > 0), (if (b.size() > 0), (if (c.size() > 0), (if (d.size() > 0));
我知道这段代码非常错误,但它只是让你了解我所追求的是什么。
例如,您可以在std::initalizer_list
(或std::vector
,任何您喜欢的方式)中传递地图。然后在函数内部循环a()
每个映射并检查它是否为空:
#include <initializer_list
#include <iostream>
#include <map>
void a(std::initializer_list<std::map<int, int>> maps)
{
for (const auto& m : maps) {
if (m.empty()) {
std::cout << "was emptyn";
}
else {
std::cout << "was not emptyn";
}
}
}
int main()
{
std::map<int, int> foo1;
std::map<int, int> foo2;
std::map<int, int> foo3;
std::map<int, int> foo4;
foo1[5] = 1;
foo2[9] = 3;
a({foo1, foo2, foo3, foo4});
return 0;
}
输出:
was not empty was not empty was empty was empty
现场观看
该函数需要一个参数包,因此我可以发送多少或多少 我想要的元素。有没有办法在 电话本身?
除了将辅助函数与std::initalizer_list
一起使用之外,还可以为此使用旧的(递归)可变参数模板。只需提供一个辅助func
,该辅助程序获取要传递原始func
的映射参数包。
namespace helper
{
void func() {} // base case
template <typename Map0, typename... Maps>
void func(const Map0& firstMap, const Maps& ... restMaps)
{
if (!firstMap.empty()) {
// not empty case: call ::func(firstMap); here
}
helper::func(restMaps...); // do check for the rest of the map
}
}
这使得函数调用为:
std::map<int, int> a, b, c, d;
helper::func(a, b, c, d);
(见在线)
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类