Reputation: 6818
I have this code:
struct MultiMemoizator {
template <typename ReturnType, typename... Args>
ReturnType callFunction(std::function<ReturnType(Args...)> memFunc, const Args&... args) {
return memFunc(args ...);
}
};
int main()
{
typedef vector<double> vecD;
//filling vecD with random numbers...
MultiMemoizator mem;
function<vecD(vecD)> sort_vec = [](vecD &vec) {
sort(vec.begin(),vec.end());
return vec;
};
mem.callFunction<vecD,vecD>(sort_vec,vec);
//vec is still not sorted!
}
Since memFunc(args ...);
what happens is that a copy of args
is sorted and not vec
, so at the end vec
will be unsorted after callFunction(...)
.
I think that in order to solve this problem forward
can help me, but if I try: return cachedFunc(forward<Args>(args) ...);
then something bad happens (like vector::size=0
).
How can I forward args
reference to sort_vec
?
Upvotes: 0
Views: 49
Reputation: 2462
specify return type as Type&
or const Type&
and return something that is not a temporary value.
Like this:
function<vecD&(vecD&)> sort_vec = [](vecD &vec) -> vecD& {
std::sort(vec.begin(),vec.end());
return vec;
};
p.s. you vere trying to sort const
vector.
Upvotes: 1