问题描述
我正在寻找一元函子,该函子将取消引用它的参数并返回结果.当然,我可以写一个,似乎应该已经存在了.
I'm looking for a unary functor which will dereference it's argument and return the result. Of course I can write one, it just seemed like something should already exist.
因此给出了代码:
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; });
我希望有一个可以代替lambda的仿函数.这样的事情是否存在,还是我只需要使用lambda?
I was hoping that there was a functor that I could use instead of the lambda. Does such a thing exist, or do I need to just use the lambda?
推荐答案
假定"functor" 是指功能对象" 或可调用对象",标准库中似乎没有您想要的东西.
自己实现它很简单:
struct deferencer
{
template <typename T>
decltype(auto) operator()(T&& x) const
noexcept(noexcept(*x))
{
return *x;
}
};
请注意,您的lambda并没有达到您的期望,因为它的隐式返回类型为-> auto
,它会进行复制.一种可能的正确lambda是:
Note that your lambda doesn't do what you expect, as its implicit return type is -> auto
, which makes a copy. One possible correct lambda is:
[](const auto& i) -> decltype(auto) { return *i; }
如果您没有为lambda指定显式的跟踪返回类型,则隐式的将是auto
,它始终是副本. operator*
返回引用无关紧要,因为lambda返回副本(即operator*
返回的引用然后由lambda的return
语句复制).
If you don't specify an explicit trailing return type for a lambda, the implicit one will be auto
which is always a copy. It doesn't matter if operator*
returns a reference, since the lambda returns a copy (i.e. the reference returned by operator*
is then copied by the lambda's return
statement).
struct A
{
A() = default;
A(const A&) { puts("copy ctor\n"); }
};
int main()
{
[]{ return *(new A); }(); // prints "copy ctor"
}
这篇关于是否有间接函子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!