vendredi 28 octobre 2016

std::packaged_task from a lambda function with a parameter by reference

I want to package a simple function that reads a file and does some other things to it to pass it to a thread. The following gives me an error in g++.

std::packaged_task<int(std::string,std::string)> readFileTask(
                              [](const std::string& filename,
                                  std::string& filedata) -> int
        {
            //call something like ReadFile(filename,filedata);
            //the second parameter will get the data from the file
            //do other stuff
        });

The error is not so informative:

/usr/include/c++/4.9/functional:1665: error: no type named 'type' in 'class std::result_of<std::reference_wrapper<MainWindow::sendFile(const QString&)::<lambda(const string&, std::string&)> >(std::basic_string<char>, std::basic_string<char>)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^

This can be fixed by removing the non-const string. The following compiles!

std::packaged_task<int(std::string)> readFileTask(
                              [](const std::string& filename) -> int
        {
        });

So it's just that when there's a non-const reference, it complains. Why?

How can I package a lambda with a non-const reference?

Aucun commentaire:

Enregistrer un commentaire