假设我有一个函数 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...);
}
有什么方法可以针对不同类型实现这一点吗?
有什么方法可以针对不同类型实现这一点吗?
完全按照您编写的方式工作。
但是,如果您可以使用 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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句