Search code examples
c++argumentsweak-ptr

Simple Argument Forwarding (what should my signature be?)


As an example, say I am writing a thin wrapper for a vector's push_back method.

class Foo
{
public:
   void myPushBack(Bar b);   // Line in question
private:
   std::vector<Bar> vec;
}

void Foo::MyPushBack(bar b)
{
   vec.push_back(bar);
}

main()
{
   Foo f();
   f.myPushBack();
}

My question is what is the correct signature for the function myPushBack? Then my next question is what would be the correct signature for the function myPushBack if vec was of type std::vector<weak_ptr<Bar>>?


Solution

  • Assuming that you are using C++11, you should use the perfect forwarding idiom:

    template<typename T> void Foo::MyPushBack(T &&b)
    {
       vec.push_back(std::forward<T>(b));
    }
    

    Since it is a template, it does not matter the actual type of the vector. It will even take into account implicit conversions, such as const char* to std::string.