3

I stumbled upon this while trying something equivalent to

#include <vector>
#include <algorithm>

struct pred { //not copyable
    pred () {}
    bool operator()(int) const { return false; }
    pred( pred && ) {}
};

int main () {
    std::vector<int> a{1,2,3};
    std::vector<int> b{};
    auto p = pred{};
    //std::copy_if(a.begin(), a.end(), std::back_inserter(b), p); // this fails
    std::copy_if(a.begin(), a.end(), std::back_inserter(b), std::move(p));
}

see https://godbolt.org/z/wDvO3K

Why can stl algorithms not accept universal references for the "operations"?

PS: Apologies if this is a duplicate, I would be surprised if it isn't..

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
nnolte
  • 1,628
  • 11
  • 25
  • `std::copy_if(a.begin(), a.end(), std::back_inserter(b), pred());` – DimChtz Sep 24 '19 at 09:03
  • 3
    Relevant/duplcate https://stackoverflow.com/questions/48803927/why-does-stdfind-iffirst-last-p-not-take-predicate-by-reference – StoryTeller - Unslander Monica Sep 24 '19 at 09:04
  • well sure @DimChtz, but that was not the question ^^ – nnolte Sep 24 '19 at 09:05
  • so, @StoryTeller, would you say that universal references would make sense nowadays? – nnolte Sep 24 '19 at 09:11
  • 2
    @kawillzocken - If it was designed from scratch today, maybe. But given the changes to the core language, there is practically nothing lost by keeping it a value. – StoryTeller - Unslander Monica Sep 24 '19 at 09:17
  • 2
    An extract of the answer from the linked post which explains the reference part: "So up to c++11, we don't really have an alternative. A pass by value would be better than a reference. With the new standard, we may revise our approach. To support rvalues, we may add an rvalue reference overload. By passing a value, the caller has the choice in how to create it, and for prvalues, in c++17, it's practically free. If the caller so desires, they can provide referential semantics explicitly. So nothing is lost, and I think much is gained in terms of simplicity of usage and API design" – Sisir Sep 24 '19 at 09:26

0 Answers0