Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 839
Ankit Acharya Avatar asked Nov 24 '15 16:11

Ankit Acharya


2 Answers

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));
like image 86
Dewfy Avatar answered Oct 04 '22 17:10

Dewfy


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.

like image 24
Baum mit Augen Avatar answered Oct 04 '22 19:10

Baum mit Augen