Is there a way to guidance?

I am looking for a unary functor that will dereference its argument and return a result. Of course, I can write one, it just seemed that something should already exist.

So, set the code:

const auto vals = { 0, 1, 2, 3 }; vector<const int*> test(size(vals), nullptr); iota(begin(test), end(test), data(vals)); transform(cbegin(test), cend(test), ostream_iterator<int>(cout, " "), [](const auto& i){ return *i; }); 

Live example

I was hoping there was a functor that I could use instead of lambda. Is there such a thing, or do I just need to use lambda?

+6
source share
1 answer

Assuming that by “functor” you mean “function object” or “called object”, it does not seem to be what you want in the Library standard .

It is trivial to implement it yourself:

 struct deferencer { template <typename T> decltype(auto) operator()(T&& x) const noexcept(noexcept(*x)) { return *x; } }; 

Note that your lambda does not do what you expect, since its implicit return type -> auto , which makes a copy. The correct lambda is possible:

 [](const auto& i) -> decltype(auto) { return *i; } 

If you do not specify an explicit return type for the lambda, implicit will be auto , which will always copy . It doesn’t matter if operator* returns a link, because the lambda returns a copy (that is, the link returned by operator* is then copied by the lambda operator return ).

 struct A { A() = default; A(const A&) { puts("copy ctor\n"); } }; int main() { []{ return *(new A); }(); // prints "copy ctor" } 

wandbox example

+9
source

Source: https://habr.com/ru/post/1013796/


All Articles