Apply function on each element in parameter pack

Deadly 提交于 2019-12-05 15:20:56

问题


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

Is there any way to convert the parameter pack using the convert function as in the comment?

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.


回答1:


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

Where something(convert(args)...) is a parameter pack expansion that expands to:

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

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


来源:https://stackoverflow.com/questions/47848910/apply-function-on-each-element-in-parameter-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!