Skip to main content

Posts

Showing posts from June, 2012

Perfect Forwarding of Parameter Groups in C++11

C++11 offers a great new feature called Perfect Forwarding , which is enabled via the use of rvalue references. Perfect forwarding allows a function template to pass its arguments through to another function while retaining the original lvalue/rvalue nature of the function arguments. It avoids unnecessary copying and avoids the programmer having to write multiple overloads for different combinations of lvalue and rvalue references. A class can use perfect forwarding with variadic templates to "export" all possible constructors of a member object at the parent's level. class Blob { std::vector<std::string> _v; public: template<typename... Args> Blob(Args&&... args) : _v(std::forward<Args>(args)...) { } }; int main(void) { const char * shapes[3] = { "Circle", "Triangle", "Square" }; Blob b1(5, "C++ Truths"); Blob b2(shapes, shapes+3); } The Blob class above contains a std::vecto