How to use template function parameter in std::bind?

2.5k views Asked by At

i am trying to create a function that parallelize a for. I am using the Thread of the SFML and std::bind with template.

Here is what i tried.

#include <SFML/System.hpp>

#include <iostream>
#include <functional>
sf::Mutex mutex;

template <typename F>
void For_Multitread(F Function, std::vector<int>& A);

template <typename F>
void Execute_For(F Function, std::vector<int>& A, int Depart, int Fin);
void Compute(int& Number);

template <typename F>
void For_Multitread(F Function, std::vector<int>& A)
{
    for (int Thread = 0; Thread < 2; Thread++)
    {
        sf::Thread thread(std::bind(&Execute_For, Function, A, Thread * 5, (Thread+1)*5));
        thread.launch();
    }

    mutex.lock();

    for (int i = 0; i < 10; ++i)
        std::cout << A[i] << std::endl;

    mutex.unlock();
}

template <typename F>
void Execute_For(F Function, std::vector<int>& A, int Depart, int Fin)
{
    for (int i = Depart; i < Fin; ++i)
    {
        Function(A[i]);
    }
}

void Compute(int& Number)
{
    Number++;
}

int main()
{
    std::vector<int> A;
    for (int i =0; i < 10; i++)
        A.push_back(i);

    For_Multitread(&Compute, A);

    return 0;
}

The error is

no matching function for call to 'bind(<unresolved overloaded function type>, void (*&)(int&), std::vector<int>&, int, int)

Did i miss something really important ?

1

There are 1 answers

0
Piotr Skotnicki On BEST ANSWER

Execute_For is a function template, therefore you need to either supply it with type template arguments:

std::bind(&Execute_For<F>, Function, A, Thread * 5, (Thread+1)*5)
//        ~~~~~~~~~~~~~~^            

or use a static_cast:

std::bind(static_cast<void(*)(F,std::vector<int>&,int,int)>(&Execute_For), Function, A, Thread * 5, (Thread+1)*5)
//        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^