I have a map, that I only want to send to a function if it has elements in it. The function takes a parameter pack so I can send how many or how few elements I want.
Is there a way to make the size-check of the map in the call itself? There are a lot of maps that will be sent in the same call meaning that it would be very tedious to do the check outside of the call itself.
pseudo-code of what I want:
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));
I know this code is very wrong, but it is just to give you an idea of what I am after.
You can for example pass the maps in a std::initalizer_list
(or std::vector
, whatever you prefer). And then inside the function a()
loop over each map and check if it was empty:
#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 empty\n";
}
else {
std::cout << "was not empty\n";
}
}
}
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;
}
Output:
was not empty was not empty was empty was empty