如何在std :: bind中使用模板函数参数?

时间:2014-11-17 20:43:07

标签: c++ multithreading templates c++11 stdbind

我正在尝试创建一个并行化for的函数。 我正在使用SFML的Thread和std :: bind with template。

这是我尝试过的。

#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;
}

错误是

  

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

我是否错过了一些非常重要的内容?

1 个答案:

答案 0 :(得分:3)

Execute_For函数模板,因此您需要为其提供类型模板参数:

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

或使用static_cast

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