Needless to over explain. The following code is self-evident:
struct X
{
X(int n){}
};
int main()
{
std::vector<int> src;
std::vector<X> dest;
// Below is not valid in current C++, but that is just what I want.
transform(src.begin(), src.end(), back_insert(dest), std::bind(&X::X, _1));
}
A constructor takes some arguments and returns an object of the class of the constructor.
A constructor looks like a function, acts like a function, and is exactly a function.
So, I think std::bind should uniformly treat constructors and other callable objects.
However, how can I extend the function template "bind" to implement that?
std::bind. The function template bind generates a forwarding call wrapper for f . Calling this wrapper is equivalent to invoking f with some of its arguments bound to args .
boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.
std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.
Bind function with the help of placeholders helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output.
Build a factory function. These are static member functions or stand-alone functions that also construct objects, usually after validating inputs. They're useful whenever you want to ensure your objects cannot be built with invalid input (after all, you cannot abort construction within a ctor).
Since a factory is an ordinary function, you can easily bind to it to get the same effect you appear to want- a bound function that builds objects.
class X
{
public:
X(OtherObject a, OtherData data);
virtual ~X() {}
};
// Factory- return "X" instead of "X*" if not using the heap
X* CreateX(OtherObject a, OtherData data) {
/*
Logic that checks a, data for validity...
*/
if(invalid) {
return 0; // You get no object
}
return new X();
}
Now you just bind to "CreateX" to build objects. It is a normal function, however, not a constructor so all the normal rules for functions apply- especially those for copy and move construction of objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With