Given:
#include <iostream>
#include <functional>
template<class T> // Just for overloading purposes
struct behaviour1 : std::reference_wrapper<T const>
{
using base_t = std::reference_wrapper<T const>;
using base_t::base_t;
// This wrapper will never outlive the temporary
// if used correctly
behaviour1(T&& t) : base_t(t) {}
};
template<class T>
behaviour1(T&&) -> behaviour1<std::decay_t<T> >;
struct os_wrapper : std::reference_wrapper<std::ostream>
{
using std::reference_wrapper<std::ostream>::reference_wrapper;
template<class T>
os_wrapper& operator<<(behaviour1<T> const& v)
{
*this << v.get(); // #1
return *this;
}
template<class U>
os_wrapper& operator<<(U&& t)
{ this->get() << t; return *this; }
};
int main() { os_wrapper(std::cout) << behaviour1(3); }
在第 #1 行中,是实际执行的间接寻址,考虑到特定的用例(立即解包的包装器,并且既不复制也不绑定到除函数参数之外的本地引用),或者编译器只是检测到对象立即解包并且只使用原始对象代替?否则哪一个设计会更好(例如,仅保存对象副本的标量类型的部分特化是否会更有效)?
我特别感兴趣gcc
(版本 7,-O3 -std=c++17
)虽然我猜两者都是clang
and gcc
执行类似的优化技术。
使用方法的预期成本std::reference_wrapper
在优化构建中是 0 因为所有std::reference_wrapper
代码可以内联。语句的汇编输出os_wrapper(std::cout) << behaviour1(3); is https://godbolt.org/g/pFSAeF:
movl $3, %esi
movl std::cout, %edi
call std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
内联是 Stroustrup 喜欢提到的零开销抽象的实现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)