Rohith R
Rohith R

Reputation: 1329

thread not working for function with template arguments

I am trying to implement multithreaded merge sort, but my attempt is fails to compile. Here is my code :

template <class RandomAccessIterator>
void merge_sort (RandomAccessIterator begin,RandomAccessIterator end)
{
    int N = end - begin;
    int N1,N2;

    if (N == 1)
        return;

    RandomAccessIterator mid = begin + (end-begin)/2;


    // merge_sort (begin,mid); // this is OK
    // merge_sort (mid,end);   // this is OK

    thread t1 (merge_sort,begin,mid); // error
    thread t2 (merge_sort,mid,end);   // error

    t1.join ();
    t2.join ();

    N1 = mid - begin;
    N2 = end - mid;

    merge (begin,N1,mid,N2);
}

Errors Messages from gcc (g++ -std=c++11 merge-multithread.cpp):

merge-multithread.cpp: In instantiation of ‘void merge_sort(RandomAccessIterator, RandomAccessIterator) [with RandomAccessIterator = int*]’:
merge-multithread.cpp:76:25:   required from here
merge-multithread.cpp:60:33: error: no matching function for call to ‘std::thread::thread(<unresolved overloaded function type>, int*&, int*&)’
  thread t1 (merge_sort,begin,mid);
                                 ^
In file included from merge-multithread.cpp:4:0:
/usr/include/c++/5.2.0/thread:133:7: note: candidate: template<class _Callable, class ... _Args> std::thread::thread(_Callable&&, _Args&& ...)
       thread(_Callable&& __f, _Args&&... __args)
       ^
/usr/include/c++/5.2.0/thread:133:7: note:   template argument deduction/substitution failed:
merge-multithread.cpp:60:33: note:   couldn't deduce template parameter ‘_Callable’
  thread t1 (merge_sort,begin,mid);
                                 ^
In file included from merge-multithread.cpp:4:0:
/usr/include/c++/5.2.0/thread:128:5: note: candidate: std::thread::thread(std::thread&&)
     thread(thread&& __t) noexcept
     ^
/usr/include/c++/5.2.0/thread:128:5: note:   candidate expects 1 argument, 3 provided
/usr/include/c++/5.2.0/thread:122:5: note: candidate: std::thread::thread()
     thread() noexcept = default;

Upvotes: 2

Views: 1237

Answers (1)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48527

merge_sort itself is a function template; to get the address of one of the instantiated functions you need to specify all template arguments:

thread t1 (&merge_sort<RandomAccessIterator>,begin,mid);
//         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

or use a static cast:

thread t1 (static_cast<void(*)(RandomAccessIterator,RandomAccessIterator)>(&merge_sort),begin,mid);

...or use a lambda expression and let the compiler automatically deduce the types of arguments:

thread t1 ([begin,mid]{merge_sort(begin, mid);});

Upvotes: 6

Related Questions