0

Please consider this code, which I obtained from another of my questions:

#include <thread>

using namespace std;

class CObject {};
void MyThreadFunc(CObject&) {}

void MyThreadFunc(CObject&&){}

template<typename FunctionType, typename ...Args>
void StartDetachedThread(FunctionType func, Args&&... args)
{
    thread([&]()
    {
        func(forward<Args>(args)...);
    }).detach();
}

int main()
{
    CObject object;
    StartDetachedThread<void(CObject&)>(MyThreadFunc, std::ref(object));

    CObject object2;
    StartDetachedThread<void(CObject&&)>(MyThreadFunc, std::move(object2));
    return 0;
}

The calls to StartDetachedThread has the template argument specified in order that if I pass an r-value reference through to it, it calls the version of MyThreadFunc that expects an r-value reference; the same for the normal reference version.

Quite simply, I don't understand how it works when I have only specified one template argument type (the type of the function I want my thread to run) to a function that expects two - can someone please clarify?

Wad
  • 1,454
  • 1
  • 16
  • 33
  • 1
    If I understand your question correctly, you need to get back to a [good book on C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). Template Argument Deduction should be covered by one. – StoryTeller - Unslander Monica Jan 21 '18 at 20:15
  • Yes I'm aware of TAD but I've never seen it in action for just a single argument being deduced whilst one is specified. I've googled but haven't found anything...what I was looking for was someone who knows what I should be looking for to point me at a quote that answers this... – Wad Jan 21 '18 at 20:16
  • Your function doesn't expect two. It expects at least one, and can get a theoretically unbounded number of arguments. That's a template parameter pack there at the end. – StoryTeller - Unslander Monica Jan 21 '18 at 20:18
  • It's really no different than a one-template-argument function, where the compiler uses the function call arguments to deduce the template type. Template deduction is template deduction. – Some programmer dude Jan 21 '18 at 20:18
  • RIght, so the compiler is smart enough to figure the type of the second template argument from my second argument, but it needs a little shove in the right direction for the first because there are two possible matches? – Wad Jan 21 '18 at 20:22
  • OK I think I get it now, if someone could post an answer I'd be much obliged... – Wad Jan 21 '18 at 21:28

1 Answers1

0

OK, nobody wants to post an answer, so I'll answer this. As noted in the comments above, the compiler will deduce the type of the argument Args via template argument deduction; it is not necessary to explicitly state all template arguments.

Wad
  • 1,454
  • 1
  • 16
  • 33