Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 对参数包中的每个元素应用函数_C++_Templates_Metaprogramming_Variadic Templates - Fatal编程技术网

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

C++ 对参数包中的每个元素应用函数,c++,templates,metaprogramming,variadic-templates,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(); } //将参数

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

// 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();
}
//将参数传递给。。。
模板
U转换(T&T){
返回std::向前(t);
}
// ... 但是转换std::字符串
常量字符*转换(标准::字符串s){
返回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.
}
模板
无效剂量测量(Args…Args){
//使用上面的转换函数转换参数包
//并使用
//转换后的args。
}
是否有任何方法可以使用注释中的convert函数转换参数包

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

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

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

模板
void doSomething(Args&…Args){
某物(convert(std::forward(args))…);
}

btw,您的
doSomething
不接受转发引用,而
convert
意味着它应该接受转发引用。另外
convert(std::string)
返回一个悬空指针。因此,您可能需要做一些更改。@StoryTeller如果我按照建议只想打印它,我假设指针可以,因为我不打算保留它?
s
是本地转换的。怎么可能呢?@StoryTeller ok我看到字符串是按值取的,我可以用引用代替。
// pseudocode
something(convert(arg0), convert(arg1), convert(arg2), ...)
template<typename... Args>
void doSomething(Args&& ... args) {
  something(convert(std::forward<Args>(args))...);
}