简体   繁体   English

完美的转发困境

[英]perfect forwarding dilemma

say I have this struct: 说我有这个结构:

template <typename ...A>
struct A
{
  void f(A&& ...args)
  {
    fwd(std::forward<A>(args)...);
  }

  template <typename ...B>
  void g(B&& ...args)
  {
    fwd(std::forward<B>(args)...);
  }
};

Will f and g both forward perfectly, if A... == B... ? 如果A... == B...fg都会完美地前进吗? IMO, they should, but I am just asking to be sure. IMO,他们应该,但我只是要求确定。

EDIT: The reason for this question is the common lecture about how perfectly forwarding functions should always be template functions. 编辑:这个问题的原因是关于完美转发功能应该始终是模板功能的常见讲座。 Obviously this is not true for f . 显然f不是这样。

Will f and g both forward perfectly, if A... == B... ? 如果A... == B...fg都会完美地前进吗?

Yes. 是。 I see no reason whatsoever for which they shouldn't. 我认为没有理由不应该这样做。

Yes, if A... == B... , there is no difference in behaviour. 是的,如果A... == B... ,行为没有区别。 However, the reason for the common advice about forwarding functions needing to be templated is that you would rather have the compiler deduce the types(as in the case of a function template) instead of you having to specify the correct types(as in the case of a class template). 但是,关于需要模板转发函数的常见建议的原因是您希望编译器推导出类型(如函数模板的情况),而不是必须指定正确的类型(如在案例中)一个类模板)。 This difference is illustrated by the following snippet for a type X (of course, they don't satisfy A... == B... ) : 这种差异通过以下X类型的片段来说明(当然,它们不满足A... == B... ):

X x;
A<X>::f(X());
A<X>::g(X());//here, f and g have the same behaviour

A<X>::f(x);//fails to compile, since A<X>::f expects an rvalue ref.
A<X>::g(x);//works as expected - Here, B... = X&, while A... = X.

A<const X&>::f(X());//oh noes! fwd gets a const X&.
A<const X&>::g(X());//forwards correctly as B... = X, even though A... = const X&.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM