【问题标题】:Is it possible to build variadic template with different types?是否有可能构建具有不同类型的variadic模板?
【发布时间】:2019-07-25 05:42:23
【问题描述】:

假设我有一个函数write(ostream& s, T& val)

我可以在不同的数据上多次调用 write:

write(s, 5);
write(s, 2.5);
write(s, "abc");

相反,我想要一个可变参数列表,只需一次调用即可生成上述内容:

write(s, 5, 2.5, "abc");

我可以为单一类型做到这一点:

template<typename T, typename... Args>
void write(ostream& s, T first, Args... args) {
    write(s, first);
    write(s, args...);
}

有没有办法针对不同的类型实现这一点?

【问题讨论】:

  • 此代码适用适用于不同类型。
  • 另见godbolt.org/z/JwS-PX - 你的代码在行动;-)
  • 这个代码帽不起作用是怎么回事?您是否收到编译器错误?还是没有给出预期的输出?你能提供一个完整的工作示例吗?

标签: c++ c++11 templates recursion variadic-templates


【解决方案1】:

有没有办法针对不同的类型实现这一点?

完全按照你写的那样工作。

但是,如果你可以使用 C++17,我建议避免递归并使用模板折叠,如下所示

template <typename ... Args>
void write (std::ostream& s, Args ... args)
 { (..., write(s, args)); }

如果只能使用 C++11 或 C++14,则可以模拟模板折叠初始化未使用的数组

template <typename ... Args>
void write (std::ostream& s, Args ... args)
 {
   using unused = int[];

   (void)unused { 0, (write(s, args), 0)... };
 }

无论如何,递归方式的完整工作示例

#include <iostream>

template <typename T>
void write (std::ostream & s, T const & t)
 { s << "- " << t << std::endl; }

template <typename T, typename ... Args>
void write (std::ostream& s, T first, Args ... args)
 { write(s, first); write(s, args...); }

int main ()
 {
    write(std::cout, 1, 2.2, "three", 4l);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2019-11-10
    • 2020-08-13
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多