简体   繁体   中英

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

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 ?

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)
//        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM