Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic binding for boost::thread in C++?

Tags:

c++

boost

When doing:

std::vector<int> vec;
int number = 4;
boost::thread workerThread(&Method, number, vec)

given a method:
template<typename T>
void Method(int n, std::vector<T> & vec)
{
    //does stuff
}

Why do I have to manually do:

boost::thread workerThread(&Method, number, boost::ref(vec))?

Why does it not automatically pass it by reference?

Edit:: so would it be possible theoretically for boost::thread to do some macro-meta-programming to adjust this since C++ has nothing in the way of built in reflection/introspection.

So is a major part of boost / C++ in general passing meta-information around?

like image 324
Eiyrioü von Kauyf Avatar asked Jun 28 '13 15:06

Eiyrioü von Kauyf


1 Answers

Because the boost::thread object cannot determine the signature of Method.

He only knows the types of the arguments being passed in and will forward them to the provided function. If the types don't match you get a nice complicated error message at the place where boost::thread attempts to call the function.

When looking at the types of the arguments, it is impossible to differ between pass-by-reference and pass-by-value as they look the same from the caller's side. Or from a more formal perspective: In template argument deduction T& will decay to T.

Only by providing the explicit boost::ref on the caller's side boost::thread will be able to correctly identify the type as a reference type.

like image 146
ComicSansMS Avatar answered Nov 01 '22 21:11

ComicSansMS