I noticed that make_shared() does something neat and i am wonderng how this works … make_shared() copies and validates the argument list for the constructors of T. How does this work? How is it possible to design my own template function which copies and validates the available constructors for T?
example:
#include <memory>
#include <iostream>
#include <string>
using namespace std;
class Department
{
public:
string Name;
double Budget;
Department(const string& name, const double& budget);
};
Department::Department(const string& n, const double& b)
: Name(n), Budget(b)
{
cout << Name << " : " << Budget << endl;
}
int main()
{
shared_ptr<Department> d = make_shared<Department>("Human Resources", 1000.0);
// shared_ptr<Department> d = make_shared<Department>(); NOT VALID
return 0;
}
The above validates at compile time that make_shared(); uses the arguments const string& and const double&. How could I mimic this behaviour in my own code?
This is done using perfect forwarding (
std::forward()). You can read about it here (make sure you continue reading to the solution in the next page) and here