TRY IT OUT: Perfect Forwarding
This example uses the string class that I’ll discuss in detail at the end of this chapter. In addition to showing perfect forwarding in action, the example demonstrates defining a template function as a member of a non-template class, and using a template with two type parameters. The example defines a Person class like this:
class Person
{
public:
  // Constructor template
  template<class T1, class T2>
  Person(T1&& first, T2&& second) :
    firstname(forward<T1>(first)), secondname(forward<T2>(second)) {}
//    firstname(first), secondname(second) {}
 
  string getName() const
  {
    return firstname.getName() + " " + secondname.getName();
  }
 
private:
  Name firstname;
  Name secondname;
};
This is an ordinary class with the constructor defined by a template with two type parameters, T1 and T2. This allows the constructor arguments to be of different types — type string and type char*, for example. The data members that store the first and second name of a person are of type Name; I’ll define the Name class in a moment. The Person constructor initializes the data members with the arguments after passing them to std::forward() from the utility header. This will ensure that an rvalue reference argument will remain as an rvalue reference when it is used to initialize a Person class data member. I’ll come back to the commented-out line later. The getName() member returns a string representation of a Person object.
Here’s the Name class definition:
class Name { public: ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.