Is There a Indirection Functor?

无人久伴 提交于 2019-12-05 05:47:50

Assuming that by "functor" you mean "function object" or "callable object", there doesn't seem to be what you desire in the Standard Library.

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 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; }

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"
}

wandbox example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!