Search code examples
c++stdbind

How do I bind arguments to a constructor?


As described above, I want to use std::bind to create a function that, when called, returns an object built with a constructor with default parameters like below:

#include <functional>

class X
{
    int x_, y_;
    public:
    X(int x, int y): x_(x), y_(y)
    {
    }
};

int main() {
    auto fun = std::bind(&X::X, 1, 2);
    X x = fun();   
}

Instead I get the following compiler errors:

error: qualified reference to 'X' is a constructor name rather than a type in this context

error: expected '(' for function-style cast or type construction In reference to this line:

auto fun = std::bind(&X::X, 1, 2);

Solution

  • Comments answer this question. Apparently std::bind cannot be used with constructors and destructors because they can't have their address taken. Thank you to Eugene, The Philomath, and molbdnilo.