C++ 如何对可变参数函数中的所有参数调用 std::forward?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2821223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would one call std::forward on all arguments in a variadic function?
提问by Edward Strange
I was just writing a generic object factory and using the boost preprocessor meta-library to make a variadic template (using 2010 and it doesn't support them). My function uses rval references and std::forward
to do perfect forwarding and it got me thinking...when C++0X comes out and I had a standard compiler I would do this with real variadic templates. How though, would I call std::forward
on the arguments?
我只是在编写一个通用对象工厂并使用 boost 预处理器元库来制作一个可变参数模板(使用 2010 并且它不支持它们)。我的函数使用 rval 引用并std::forward
进行完美转发,这让我开始思考……当 C++0X 出现并且我有一个标准编译器时,我会用真正的可变参数模板来做到这一点。但是,我会如何呼吁std::forward
争论?
template <typename ...Params>
void f(Params... params) // how do I say these are rvalue reference?
{
y(std::forward(...params)); //? - I doubt this would work.
}
Only way I can think of would require manual unpacking of ...params and I'm not quite there yet either. Is there a quicker syntax that would work?
我能想到的唯一方法是手动解包 ...params ,而且我还没有到那里。有没有更快的语法可以工作?
回答by GManNickG
You would do:
你会这样做:
template <typename ...Params>
void f(Params&&... params)
{
y(std::forward<Params>(params)...);
}
The ...
pretty much says "take what's on the left, and for each template parameter, unpack it accordingly."
在...
相当多说,“采取什么样的左边,并为每个模板参数,因此解压。”