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

Apply function on each element in parameter pack

我有以下专门化的模板函数:

// 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();
}

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

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.
}

有没有像评论中那样使用转换函数转换参数包的方法?

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

template<typename ... Args>
void doSomething(Args ... args) {
  something(convert(args)...);
}

其中 something(convert(args)...)parameter pack expansion 扩展为:

// pseudocode
something(convert(arg0), convert(arg1), convert(arg2), ...)

顺便说一句,您可能希望通过 转发引用 来获取 args 以避免不必要的复制并正确传播 左值引用 :

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