boost::thread and template functions
I am trying to run a template function on a separate thread but Intell开发者_运维技巧iSense (VC++ 2010 Express) keeps giving me the error: "Error: no instance of constructor "boost::thread::thread" matches the argument list" and if I try to compile I get this error: "error C2661: 'boost::thread::thread' : no overloaded function takes 5 arguments"
The error has only occurred since I added the templates so I'm certain it has something to do with them but I don't know what.
Two of the arguments I am passing to boost::thread are template functions defined as:
template<class F>
void perform_test(int* current, int num_tests, F func, std::vector<std::pair<int, int>>* results);
and:
namespace Sort
{
template<class RandomAccessIterator>
void quick(RandomAccessIterator begin, RandomAccessIterator end);
} //namespace Sort
I try to call boost::thread like so:
std::vector<std::pair<int, int>> quick_results;
int current = 0, num_tests = 30;
boost::thread test_thread(perform_test, ¤t, num_tests, Sort::quick, &quick_results);
A template function is not a 'real' function. The compiler first needs to instantiate it. But for the compiler to do this, it needs to know the types for the template parameters you would like the function to be instantiated for. There is no way for the compiler to deduce those parameters from your code.
However, if you rewrite the code as:
typedef std::vector<std::pair<int, int>> container;
typedef container::iterator iterator;
boost::thread test_thread(
&perform_test<Sort::quick<iterator>>,
¤t,
num_tests,
&Sort::quick<iterator>,
&quick_results);
it should work.
The following version compiles and runs OK for me - the main change is to modify the perform_test
declaration so that parameter 3 is correct in the context you intend. Also to ensure there is code behind the function templates.
typedef std::vector<std::pair<int, int>> container;
template<class F>
void perform_test(int* current, int num_tests,
void(* func)(typename F, typename F), container* results)
{
cout << "invoked thread function" << endl;
}
namespace Sort
{
template<class RandomAccessIterator>
void quick(RandomAccessIterator begin, RandomAccessIterator end)
{
cout << "invoked sort function" << endl;
}
} //namespace Sort
int main()
{
container quick_results;
int current = 0, num_tests = 30;
boost::thread test_thread(
&perform_test<container::iterator>,
¤t,
num_tests,
Sort::quick<container::iterator>,
&quick_results);
test_thread.join();
return 0;
};
精彩评论