如何仅在语句匹配时才发送参数到函数?

How to send parameter to function only if statement is matched?

本文关键字:参数 函数 何仅 语句      更新时间:2023-10-16

我有一个映射,我只想在函数中有元素时才发送给它。该函数需要一个参数包,因此我可以发送我想要的元素数量或数量。

有没有办法在调用本身中对地图进行大小检查?有很多地图将在同一调用中发送,这意味着在调用本身之外进行检查将非常繁琐。

我想要的伪代码:

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);

(见在线)