Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a constructor in C++?

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?

like image 267
xmllmx Avatar asked Nov 29 '10 08:11

xmllmx


People also ask

What is the use of std :: bind?

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 .

What is boost bind?

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.

What does STD bind return?

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.

What is the use of bind in C++?

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.


1 Answers

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.

like image 148
Zack Yezek Avatar answered Sep 24 '22 21:09

Zack Yezek