6

I'm facing a problem with std::thread because it doesn't accept functions taking auto-specified arguments. Here is some sample code:

#include <iostream>
#include <vector>
#include <thread>

using namespace std;

void seev(const auto &v) // works fine with const vector<int> &v
{
    for (auto x : v)
        cout << x << ' ';
    cout << "\n\n";
}

int main()
{
    vector<int> v1 { 1, 2, 3, 4, 5 };
    thread t(seev, v1);
    t.join();
    return 0;
}

But the compiler says:

[Error] no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, std::vector<int>&)'

Why is this happening? Is it a problem with the language or GCC (4.9.2)?

James Ko
  • 32,215
  • 30
  • 128
  • 239
Ankit Acharya
  • 2,833
  • 3
  • 18
  • 29

2 Answers2

13

Think about auto as a template argument then your function looks like:

template <class T>
void seev (const T &v) ...

C++ cannot incarnate template without explicit spec of types. That is why you get an error. To fix issue (with template argument declaration) you can use:

thread t (seev<decltype(v1)>, std::ref(v1));
Dewfy
  • 23,277
  • 13
  • 73
  • 121
  • this fails too bro, try something else – Ankit Acharya Nov 24 '15 at 16:09
  • @AnkitAcharya just checked on VS-2013 compiled well. Please pay attention to my note about "(with template argument declaration)" so you have use `template void seev (const T &v)` – Dewfy Nov 24 '15 at 16:12
  • @AnkitAcharya Check [this](https://stackoverflow.com/questions/10673585/start-thread-with-member-function/10673671#10673671), third paragraph!!! – Stephan Dollberg Nov 24 '15 at 16:19
  • 4
    You can also fix this by avoid pass vector by value just use `std::ref` as follow: `thread t (seev, std::ref(v1));` http://coliru.stacked-crooked.com/a/ff9ce57149fbaa47 – Dewfy Nov 24 '15 at 16:21
  • Hey meta police, how about you delete the useless comments next time instead of my useful ones that answer his questions! – Stephan Dollberg Nov 24 '15 at 21:12
13
void seev (const auto &v)

is not valid C++ (yet, it is proposed for C++17). gcc would have told you had you compiled with -pedantic.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182