函数对象的正确参数类型是什么? [英] What is the correct argument type for a function-object?

查看:205
本文介绍了函数对象的正确参数类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板函数接收函数对象。有时,函数对象是无状态结构,但有时它们是大的有状态对象。函数对象的状态在此函数中不更改,仅进行检查。我也非常热衷于编写代码,编译器可以尽可能优化。在选择参数类型时应该考虑什么?

I have a templated function that receives function-objects. Sometimes the function-objects are stateless structs, but sometimes they are large statefull objects. The state of the function-object is not changed in this function, only examined. I'm also very keen on writing code that the compiler can optimize as much as possible. What should I consider when choosing the argument type?

函数是这种类型:

template<typename funcT>
auto make_particle(funcT fun) {
   Particle<typename funcT::result_type> particle;
   particle = fun();
   return particle;
}

参数类型应该是 funcT const& fun ,以便不会复制大对象,但为什么大多数人使用按值调用函数对象?我通过使用const引用松动的东西吗?还是应该使用lvalue-reference?请注意,c ++ 1y是确定的,上面的代码示例只是一个示例。

The argument type should probably be funcT const & fun so that the large objects are not copied, but why do most people use call-by-value function objects? Do I loose something by using const reference? Or should I use lvalue-reference? Please note that c++1y is ok and that the code example above is just an example.

推荐答案


参数类型应该是funcT const&有趣的,所以
大对象不被复制,

The argument type should probably be funcT const & fun so that the large objects are not copied,

这不是标准库中的算法。在那里,可调用对象取值。由可调用对象的作者来确保它合理地便宜地复制。例如,如果它需要访问大的东西,那么你可以让函子的用户提供一个引用并存储在函子中 - 复制引用很便宜。

That is not the view taken by the algorithms in the standard libraries. There, callable objects are taken by value. It's up to the author of the callable object to ensure that it's reasonably cheap to copy. For example if it needs access to something large, then you can have the user of the functor provide a reference to one and store that in the functor -- copying a reference is cheap.

现在,它可能是你想做的事情不同于标准库,因为你期望粒子制作功能异常困难,使廉价复制或移动。但是C ++程序员熟悉被复制的函子,所以如果你做标准库,通常你不会使他们的生活比他们已经更糟。复制函子不是问题,除非你把它做一个: - )

Now, it may be that you want to do things differently from the standard library because you expect particle-making functions to be unusually difficult to make cheap to copy or move. But C++ programmers are familiar with functors being copied, so if you do what the standard library does then usually you aren't making their lives any worse than they were already. Copying functors isn't an issue unless you make it one :-)

这篇关于函数对象的正确参数类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆