在参数包中的每个元素上应用函数

Zit*_*rax 11 c++ templates metaprogramming variadic-templates

我有以下模板功能与专业化:

// 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();
}
Run Code Online (Sandbox Code Playgroud)

如果我有一个可变参数模板函数,如:

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.
}
Run Code Online (Sandbox Code Playgroud)

有没有办法像注释一样使用convert函数转换参数包?

我最初的目标是能够在类似printf的函数中将std :: string传递给'%s',而不必先在字符串上手动调用.c_str().但是我也对一般情况感兴趣,如果这可以用一种简单的方式完成,我的尝试到目前为止都失败了.

Vit*_*meo 16

template<typename ... Args>
void doSomething(Args ... args) {
  something(convert(args)...);
}
Run Code Online (Sandbox Code Playgroud)

哪里something(convert(args)...)是一个参数包扩展用于扩展为:

// pseudocode
something(convert(arg0), convert(arg1), convert(arg2), ...)
Run Code Online (Sandbox Code Playgroud)

顺便说一下,您可能希望args通过转发引用来避免不必要的副本并正确传播左值引用:

template<typename... Args>
void doSomething(Args&& ... args) {
  something(convert(std::forward<Args>(args))...);
}
Run Code Online (Sandbox Code Playgroud)