Mano Mini
Mano Mini

Reputation: 613

Using a custom constructor as a template function

I have template function change that takes a function that takes int and returns an object of type A. So I thought I can use the constructor of A

class A {
    int y;
public:
    explicit A(int y) : y(2 * y) {

    }
};

class B {
    A x;
public:
    B(int x) : x(x) {

    }

    template<typename F>
    void change(int y, F func) {
        x = func(y);
    }

};

int main(void) {
    B b(7);
    b.change(88, A());    // << here

    return 0;
}

But the compiler says no matching function for call to ‘A::A()’

How can I make it works?

Upvotes: 0

Views: 93

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598194

You can't pass a constructor as a parameter like you are attempting. The C++ standard is very strict on not allowing the memory address of a constructor to be taken.

When you call change(88, A()), you are actually constructing a temp A object (which the compiler should not allow since A does not have a default constructor) and then you are passing that object to the parameter of change(). The compiler is correct to complain, since A does not define an operator()(int) to satisfy the call to func(y) when called in an A object.

To make this work, you need to create a separate function that constructs the A object, and then pass that function to change(), eg:

A createA(int y)
{
    return A(y);
}

int main(void) {
    B b(7);
    b.change(88, createA);
    return 0;
}

Upvotes: 3

Related Questions