仅当语句匹配时如何将参数发送给函数?

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

See it live

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?

除了使用带有 std::initalizer_list 的辅助函数外,还可以为此使用良好的旧式(递归)可变参数模板。只需提供一个 helper 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);

(See-online)