On Sun, 9 Aug 2015 19:10:43 -0700 (PDT)
> It's Listing 4.14 in C++ Concurrency in Action practical
> multithreading. It's not an easy read, but some examples seem
> useful. Any suggestion on a good intro to intermediate level book
> for C++ multithreading? Anyone? (of course in C++11)
Although I have never read it, I have heard quite good things about that
book so it is a bit worrying that it should come up with a code listing
which not only does not compile but which shows such a lack of
understanding of rvalue references, move semantics and template type
deduction. Anyway, you now have a corrected version from me. I
suggest you submit an erratum to the publisher because as I say I have
heard that the book is reasonably good on threading matters.
To be honest though, spending your time looking at a book about
multi-threading is probably not wise for someone who has yet to acquire
the basics. If you want to operate at this low level, you need to
understand rvalue references and template type deduction to understand
the code, and not just the particulars about std::packaged_task and
std::future. The basic point is that with this function signature for
perfect forwarding:
template <class T> void func(T&& t) {...}
T deduces as a reference type if passed a lvalue and a value type if
passed a rvalue. That's how forwarding works. But it does mean that
you cannot use T in the same way as you could in the C++98 days if the
signature were, say
template <class T> void func(T& t) {...}
which works completely differently - here func can only take a lvalue
and T deduces as the underlying value type, either const or non-const.
template <class T> void func(T t) {...}
does similarly, except that it discards const qualifiers and will
accept rvalues as well as lvalues (and a signature of func(const T& t)
would do the same but would differ in its treatment of volatile).
The literature on this is not that good in my opinion. Section 23.5.2
and 23.5.2.1 of Stroustrup's the C++ Programming Language (4th ed) is
unnecessarily light in content in my view. The following link is a
great deal more complete, but consequently more difficult for a
beginner to understand:
http://en.cppreference.com/w/cpp/language/template_argument_deduction
Part of the problem is probably that in C++ the use of && (rvalue
reference) has been overloaded to cover perfect forwarding by a sleight
of hand involving reference collapsing. It might have been thought
cute at the time but it is highly confusing for beginners (and also for
others, it would appear).
I also repeat the point I made before. Most C++ users don't actually
need to know about the details of template type deduction. Mostly it
just works as you would expect. But be on your guard whenever you see a
forwarding reference, where sometimes it does not.
Chris