没有第一个的 C++ 可变参数

标签 c++ function c++11 variadic

是否有可能使用不指定第一个参数的可变参数?

例如:

这段代码非常好:

void something(const char* layoutAndButton, ...)
{
    va_list ap;
    va_start(ap, layoutAndButton);
    std::map<std::string, std::string> data;
    while (*layoutAndButton != '\0') {
        std::string layout = va_arg(ap, const char*);
        ++layoutAndButton;
        std::string button = va_arg(ap, const char*);
        ++layoutAndButton;
        data.insert(std::make_pair(layout, button));
    }
    for (auto const& x : data)
    {
        std::cout << x.first << ':' << x.second << std::endl;
    }
    va_end(ap);
}

但我希望 something 以这种方式运行:

void something(const char*...)

有没有可能做那样的事情?然后访问成员?如果是,怎么办?

谢谢

最佳答案

正如评论中所述,std::initializer_list 似乎可以完成这项工作

void something(std::initializer_list<std::pair<std::string, std::string>> layoutAndButtons)
{
    // std::map<std::string, std::string> m(layoutAndButtons); // potentially
    for (auto const& p : layoutAndButtons) {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

甚至,如果您真的需要一张 map :

void something(const std::map<std::string, std::string>& layoutAndButtons)
    for (auto const& p : layoutAndButtons) {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

用法类似于:

something({{"Some", "things"}, {"are", "done"}});

如果你真的想要可变参数模板,我建议:

template<typename... Args>
void something(Args... args) 
{
    static_assert(sizeof...(Args) % 2 == 0, "wrong number of argument");
    const char* layoutAndButtons[] = {args...};

    std::map<std::string, std::string> m;
    for (auto it = std::begin(layoutAndButtons);
         it != std::end(layoutAndButtons);
         it += 2) {
        auto layout = *it;
        auto button = *(it + 1);
        m.emplace(layout, button);
    }
    for (auto const& p : m)
    {
        std::cout << p.first << ':' << p.second << std::endl;
    }
}

关于没有第一个的 C++ 可变参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47265993/

相关文章:

c++ - 使用 bool 变量和值启用功能

c++ - 静态初始化 C++

C++:在头文件中包含类定义

c - 如何正确定义函数返回的结构?

c++ - 使用字符串长度的数组大小

c++ - 如何在容器中存储(空)分配器而不占用大小?

javascript - 访问 Javascript 原型(prototype)函数

python - 如何以安全的方式从异步函数调用同步函数

c++ - 抛出异常实例后调用终止,核心转储

c++ - 是否有类型特征显示一种类型是否可能包含其他类型的值