【问题标题】:C++ variadic templates with repeating types具有重复类型的 C++ 可变参数模板
【发布时间】:2020-07-13 17:17:32
【问题描述】:

是否可以编写可变参数模板或折叠表达式,其中函数签名可以类似于

void f(int, string, int, string, ...)

这种风格在 python 中非常流行且用户友好,但我无法让它在 C++ 中工作。特别是,我会用它来为绘图函数提供数据,然后是一个标签。

编辑:展开,我想这样调用函数:

f(5, "first number");
f(5, "first number", 6, "second number");

并带有 4、6 或 ... 2*n 个参数。

【问题讨论】:

    标签: c++ templates variadic-templates


    【解决方案1】:

    你可以这样写一个可变参数函数:

    template<typename ...Ts>
    void f(int data, string const &label, Ts&&... rest)
    {
      process(data, label);
      f(std::forward<Ts>(rest...));
    }
    

    有一个基本情况:

    void f() {}
    

    终止递归。

    现在只调用形式:

    f(1, "hi");           // ok
    f(1, "hi", 2, "bye"); // ok
    // etc
    

    将编译,而:

    f(1);          // error
    f("hi");       // error
    f(1, "hi", 2); // error
    

    不会。

    【讨论】:

    • 这要求完美转发,或至少const 参考。
    【解决方案2】:

    例如,定义两个重载:

    void f() {}
    
    template<class... Ts>
    void f(int i, std::string s, Ts... ts) {
        f(std::move(ts)...); // static recursion
    }
    

    【讨论】:

    • @HolyBlackCat 好的,抱歉,这里不存在,但在更复杂的情况下,编译器很容易被 buff。
    猜你喜欢
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2015-08-09
    相关资源
    最近更新 更多