Why can't I use auto with std :: thread?

I ran into a problem with std::thread because it does not accept functions that take automatically specified arguments. Here is a 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 this a problem with the language or GCC (4.9.2)?

+6
source share
2 answers

Think of auto as a template argument, then your function will look like this:

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

C ++ cannot implement a template without an explicit type specification. This is why you get an error message. To fix the problem (with template argument declaration) you can use:

 thread t (seev<decltype(v1)>, std::ref(v1)); 
+13
source
 void seev (const auto &v) 

invalid C ++ (still it is proposed for C ++ 17). gcc would say that you compiled with -pedantic .

+13
source

All Articles