my code is like:
std::vector<bool> LevelClimberCompareMulti(std::vector<CompareArgs> &args) {
std::vector<bool> ret(args.size());
std::vector<std::shared_future<bool>> fts(args.size());
//using ArgIter = std::vector<CompareArgs>::iterator;
//using FtIter = std::vector<std::shared_future<bool>>::iterator;
std::transform(args.begin(), args.end(), fts.begin(),
[](CompareArgs& a) -> std::shared_future<bool> {return std::async(std::launch::async, &diffpng::LevelClimberCompare, a).share();});
std::transform(fts.begin(), fts.end(), ret.begin(),
[](std::shared_future<bool> ft) -> bool {return ft.get();});
return ret;
}
example:
#include <assert.h>
#include <cstdlib>
#include <cassert>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <iostream>
#include <future>
#include <mutex>
using CompareArgs = int;
namespace diffpng {
bool LevelClimberCompare(CompareArgs &args) {
return true;
}
std::vector<bool> LevelClimberCompareMulti(std::vector<CompareArgs> &args) {
std::vector<bool> ret(args.size());
std::vector<std::shared_future<bool>> fts(args.size());
//using ArgIter = std::vector<CompareArgs>::iterator;
//using FtIter = std::vector<std::shared_future<bool>>::iterator;
std::transform(args.begin(), args.end(), fts.begin(),
[](CompareArgs& a) -> std::shared_future<bool> {return std::async(std::launch::async, &diffpng::LevelClimberCompare, a).share();});
std::transform(fts.begin(), fts.end(), ret.begin(),
[](std::shared_future<bool> ft) -> bool {return ft.get();});
return ret;
}
};
int main(int argc, char** argv) {
std::vector<CompareArgs> args{1, 2, 3, 4, 5};
auto res = diffpng::LevelClimberCompareMulti(args);
for (int i = 0; i < res.size(); ++i) {
std::cout << "res[" << i << "]: " << res[i] << std::endl;
}
return 0;
}
and I get errors like that: I wonder what the error is about and how can I fix it up? btw, I am currently run it on a Win10 WSL ubuntu shell, but I dont think that has something to do with the error here. gcc version:
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
compile it simply with the cmd: g++ -std=c++14 example.cpp
you can see the error.
The arguments in std::async
are passed as temporary copies (rvalues). You can't assign an rvalue to a reference. To fix your problem you could use const ref or copy
bool LevelClimberCompare(const CompareArgs &args)
or
bool LevelClimberCompare(CompareArgs args)
You can use std::ref
or std::cref
to pass a reference
std::async(std::launch::async, &diffpng::LevelClimberCompare, std::ref(a))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.