Monday, July 17, 2017

C++11: Perfect Forwarding

This is the ability to wrap a function without creating all combinations constness overloads. Here is an example:

#include
template
void func(T i)
{
  std::cout << i << " ";;
}

template
void wrapper_without_perfect_forwarding(T& i)
{
  func(i);
}

template
void wrapper_with_perfect_forwarding(T&& i)
{
  func(std::forward(i));
}

int main()
{
  int variable = 1;
  wrapper_without_perfect_forwarding(variable);
  // wrapper_without_perfect_forwarding(2); // Error: 'void wrapper_without_perfect_forwarding(T &)':
                                                                                  //                   cannot convert argument 1 from 'int' to 'int &'
  wrapper_with_perfect_forwarding(variable);
  wrapper_with_perfect_forwarding(3);

  return 0;
}
// Output: 1 1 3


No comments:

Post a Comment