[英]String argument after parameter pack
I want to write a function write
that can take multiple arguments of any type, and print them to stdout
.我想写一个 function
write
可以采用多个 arguments 任何类型,并将它们打印到stdout
。 But I also want to pass in a delimiter as the last argument as well.但我也想传入一个分隔符作为最后一个参数。
template <typename... T>
void write(T &&...args, string delimiter) { // compilation error
((cout << args << delimiter),...);
}
Usage:用法:
write(1, ""); // single element with empty delimeter
write(1, "one", " "); // space as delimeter
write(1, "one", ","); // comma as delimeter
Right now, automatic type deduction fails since C++ expects parameter packs to be the last argument.现在,自动类型推断失败,因为 C++ 期望参数包是最后一个参数。
How can I achieve this?我怎样才能做到这一点?
There's a nice technique in this blog article which you can use.这篇博客文章中有一个很好的技术可供您使用。
Modify write
to only accept a parameter pack修改
write
只接受一个参数包
template <typename... Ts>
void write(Ts && ...args)
{
write_indirect(std::forward_as_tuple(args...),
std::make_index_sequence<sizeof...(args) - 1>{});
}
Now write_indirect
simply takes the parameter pack as a tuple, along with the indices of the arguments as template parameters.现在
write_indirect
简单地将参数包作为一个元组,连同 arguments 的索引作为模板参数。 Then it extracts the last parameter using get
, and passes that as the first parameter to write_impl
.然后它使用
get
提取最后一个参数,并将其作为第一个参数传递给write_impl
。 The remaining parameters are unpacked from the tuple, and passed as the second argument其余参数从元组中解包,并作为第二个参数传递
template<typename... Ts, size_t... Is>
void write_indirect(std::tuple<Ts...> args, std::index_sequence<Is...>)
{
auto constexpr Last = sizeof...(Ts) - 1;
write_impl(std::get<Last>(args), std::get<Is>(args)...);
}
Now write_impl
is just your original write
function but it takes the delimiter as the first argument现在
write_impl
只是你原来的write
function 但它需要分隔符作为第一个参数
template <typename... Ts>
void write_impl(std::string delimiter, Ts && ...args)
{
((std::cout << args << delimiter),...);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.