是否可以构建具有不同类型的可变参数模板?
Is it possible to build variadic template with different types?
假设我有一个函数write(ostream& s, T& val)
我可以对不同的数据多次调用写入:
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...);
}
有什么方法可以针对不同类型实现此目的吗?
Is there any way to achieve this for different types?
和你写的完全一样。
但是,如果你可以使用 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);
}
假设我有一个函数write(ostream& s, T& val)
我可以对不同的数据多次调用写入:
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...);
}
有什么方法可以针对不同类型实现此目的吗?
Is there any way to achieve this for different types?
和你写的完全一样。
但是,如果你可以使用 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);
}