17 Star 242 Fork 115

Yj / CPlusPlusThings

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
forward.cpp 1.06 KB
一键复制 编辑 原始数据 按行查看 历史
light-city 提交于 2020-03-03 11:13 . update
//
// Created by light on 19-12-15.
//
#include <iostream>
#include "../RAII/shape.h"
void overloaded( int const &arg ) { std::cout << "by lvalue\n"; }
void overloaded( int && arg ) { std::cout << "by rvalue\n"; }
template< typename t >
/* "t &&" with "t" being template param is special, and adjusts "t" to be
(for example) "int &" or non-ref "int" so std::forward knows what to do. */
void forwarding( t && arg ) {
std::cout << "via std::forward: ";
overloaded( std::forward< t >( arg ) );
std::cout << "via std::move: ";
overloaded( std::move( arg ) ); // conceptually this would invalidate arg
std::cout << "by simple passing: ";
overloaded( arg );
}
void foo(const shape&)
{
puts("foo(const shape&)");
}
void foo(shape&&)
{
puts("foo(shape&&)");
}
template <typename T>
void bar(T&& s)
{
foo(std::forward<T>(s));
}
int main() {
std::cout << "initial caller passes rvalue:\n";
forwarding( 5 );
std::cout << "initial caller passes lvalue:\n";
int x = 5;
forwarding( x );
circle temp;
bar(temp);
bar(circle());
}
C++
1
https://gitee.com/yj404/CPlusPlusThings.git
git@gitee.com:yj404/CPlusPlusThings.git
yj404
CPlusPlusThings
CPlusPlusThings
master

搜索帮助