Alex Rivera | Logout

How to bind a constructor in C++?

Asked 2010-11-29T08:32:50.813
15

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?

Edit
Report

1 Answer

4

A constructor is a member function.

A member function needs an object to be bound to.

A constructor is only called for a not-yet-existing object, so there can never be an object to bind the constructor to.

In your case, the constructor arguments (the int values from src) should go to (a possible) back_inserter that calls the non-default ctor and not to std::transform. (EDIT: this is only true for non-copy-ctor usage)

Actually, what you want to do here is to call std::copy:

std::copy(src.begin(), src.end(), std::back_inserter(dest)); 
answered 2010-11-29T08:37:25.543

Your Answer