转发参数
我有一个形式的构造:
template<class T>
void do_something_with_it(T*&& ptr)
{
//here I can do something with this ptr
}
template<class T,class... Args>
void do_something_with_them(T*&& ptr, Args&&... args)
{
do_something_with_it(std::forward<T&&>(ptr));
do_something_with_them(std::forward<Args&&>(args)...);
}
但由于某种原因我无法转发这些论点。有办法做到吗?
我正在使用 gcc 4.6.1。
I have a construct in a form:
template<class T>
void do_something_with_it(T*&& ptr)
{
//here I can do something with this ptr
}
template<class T,class... Args>
void do_something_with_them(T*&& ptr, Args&&... args)
{
do_something_with_it(std::forward<T&&>(ptr));
do_something_with_them(std::forward<Args&&>(args)...);
}
but for some reason I cannot forward those arguments. Is there a way to do it?
I'm using gcc 4.6.1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您很可能会遇到编译时错误,因为
T*&&
并不是完美的转发工具。只有T&&
是。因此,您的ptr
参数仅接受右值。除此之外,您的std::forward
应该是std::forward
,但当然现在您无论如何,还有其他错误,这无关紧要。除此之外,对do_something_with_them
的调用会错过使用零参数的do_something_with_them
的基本情况,因为如果args 为空...
如果您确实只想接受指针,则可以使用
enable_if
和is_same
或is_convertible
。但当然我不认为它是“转发”了。这样你就可以让
do_something_with_it
决定它是否接受参数(如果你愿意,你也可以将递归调用放入decltype
中。我把它作为练习向读者告知此处可能需要什么运算符)。当然,do_something_with_it
也有同样的问题,即不通用。Chances are that you get compile time errors, because
T*&&
is not a perfect forwarding vehicle. OnlyT&&
is. So yourptr
parameter only accepts rvalues. And in addition to that, yourstd::forward<T&&>
should bestd::forward<T*>
, but of course now that you have the other error anyway this is irrelevant. And in addition to that the call todo_something_with_them
misses to hit a base case ofdo_something_with_them
with zero parameters, because ifargs
is empty...If you really only want to accepts pointers, you can work with
enable_if
andis_same
oris_convertible
. But then of course I don't think it's "forwarding" anymore. What aboutThat way you let
do_something_with_it
decide whether or not it accepts the argument (if you want you can put the recursive call into thatdecltype
too. I leave it as an exercise to the reader as to what operator might be needed here). But of coursedo_something_with_it
has the same problem too about not being generic.