Вопрос

EDIT3: If I delete the second createTriangle function, it works. So how can I bind overloaded functions?

I have a function which takes a function object with one parameter, like this:

int createObject(std::function<void(int)>);

How can I call this function with std::bind? I tried it like this:

createObject(std::bind(&ClassA::createTriangle, std::placeholders::_1, a, b, c, color));

But this gives me an error:

candidate template ignored: couldn't infer template argument

ClassA::createTriangle is a static function.


Additional info:

void ClassA::createTriangle(int id, const glm::vec3 & a, const glm::vec3 & b, const glm::vec3 & c, const glm::vec3 & col) {
    /* ... */
}

int ClassB::createTriangle(const glm::vec3 & a, const glm::vec3 & b, const glm::vec3 & c, const glm::vec3 & color) {
    return classCInstance.createObject(std::bind(&classA::createTriangle, std::placeholders::_1, a, b, c, color));
}

int ClassC::createObject(std::function<void(int)> f) {
    f(++id);
    return id;
}

There is another static createTriangle function in ClassA, with a different last parameter. Is that maybe a problem? Does bind not know which createTriangle to choose? It looks like this:

void ClassA::createTriangle(int id, const glm::vec3 & a, const glm::vec3 & b, const glm::vec3 & c, const std::initializer_list<glm::vec3> & colors) {
    /* ... */
}
Это было полезно?

Решение

ClassA::createTriangle is an overloaded function, you cannot use it without specifying which overload you intend to use. std::bind has to return a generic wrapper, it cannot figure it by itself, you have to specify.

This should work:

void (*mySpecificCreateTriangle)(int, const const glm::vec3 &, const const glm::vec3 &, const const glm::vec3 &, const const glm::vec3 &) = &createTriangle;
createObject(std::bind(mySpecificCreateTriangle, std::placeholders::_1, a, b, c, color));

Since you are using C++11, you will be happier with a lambda:

createObject([=](int id){ return createTriangle(id, a, b, c, color); });
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top