在参数包中的每个元素上应用功能 [英] Apply function on each element in parameter pack
问题描述
我具有以下专门化的模板功能:
I have the following template function with specialization:
// Pass the argument through ...
template<typename T, typename U=T>
U convert(T&& t) {
return std::forward<T>(t);
}
// ... but convert std::strings
const char* convert(std::string s) {
return s.c_str();
}
如果我那时有一个可变参数模板函数,如:
If I then have a variadic template function like:
template<typename ... Args>
void doSomething(Args ... args) {
// Convert parameter pack using convert function above
// and call any other variadic templated function with
// the converted args.
}
是否可以使用注释中的convert函数转换参数包?
Is there any way to convert the parameter pack using the convert function as in the comment?
我最初的目标是能够在类似printf的函数中将std :: string传递给'%s',而不必首先手动在字符串上调用.c_str().但是我也总体上对是否可以通过简单的方式完成操作感兴趣,到目前为止,我的尝试都失败了.
My original goal was being to be able to pass std::string to '%s' in a printf like function without having to manually calling .c_str() on the strings first. But I am also interested in general if this can be done in a simple way, my tries so far failed.
推荐答案
template<typename ... Args>
void doSomething(Args ... args) {
something(convert(args)...);
}
其中something(convert(args)...)
是参数包扩展,其扩展为:
// pseudocode
something(convert(arg0), convert(arg1), convert(arg2), ...)
顺便说一句,您可能想通过转发引用来获取args
,以避免不必要的复制并正确传播左值引用:
BTW, you might want to take args
by forwarding references in order to avoid unnecessary copies and to properly propagate lvalue references:
template<typename... Args>
void doSomething(Args&& ... args) {
something(convert(std::forward<Args>(args))...);
}
这篇关于在参数包中的每个元素上应用功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!