#include <iostream>
template <typename T>
struct value {
T val;
value(T&& t) : val(std::forward<T>(t)) { }
};
//この関数は右辺値も左辺値も受けます。
//左辺値を受けたらその値を使い、右辺値だったら内部で確保したコピーを使います。
//ある変数をそのまま関数に渡してもいいですし、コピーとって右辺値にして渡してもいいです。
//コピーとって右辺値にする一番手っ取り早い方法は、同一の型にキャストすることです。(VCではダメ)
template <typename T>
value<T> makeValue(T&& x)
{
value<T> v(std::forward<T>(x));
return v;
}
value<int> helium() {
int i = 808;
auto v1 = makeValue(i); //左辺値
auto v2 = makeValue((int)i); //右辺値(VCではダメ)
std::cout << "v1.val = " << v1.val << std::endl;
std::cout << "v2.val = " << v2.val << std::endl;
i = 20140108;
std::cout << "--------------ここで i の値を変更------------" <<std::endl;
std::cout << "v1.val = " << v1.val << "(変化)" <<std::endl;
std::cout << "v2.val = " << v2.val << "(不変)" <<std::endl;
std::cout << "v2はreturnできるけどv1は i の寿命に縛られてるから無理" <<std::endl;
return v2;
}
int main() {
value<int> v = helium();
std::cout << "--------------value<int>を受け取った------------" <<std::endl;
std::cout << "v.val = " << v.val << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdGVtcGxhdGUgPHR5cGVuYW1lIFQ+CnN0cnVjdCB2YWx1ZSB7CglUIHZhbDsKCXZhbHVlKFQmJiB0KSA6IHZhbChzdGQ6OmZvcndhcmQ8VD4odCkpIHsgfQp9OwoKLy/jgZPjga7plqLmlbDjga/lj7PovrrlgKTjgoLlt6bovrrlgKTjgoLlj5fjgZHjgb7jgZnjgIIKLy/lt6bovrrlgKTjgpLlj5fjgZHjgZ/jgonjgZ3jga7lgKTjgpLkvb/jgYTjgIHlj7PovrrlgKTjgaDjgaPjgZ/jgonlhoXpg6jjgafnorrkv53jgZfjgZ/jgrPjg5Tjg7zjgpLkvb/jgYTjgb7jgZnjgIIKLy/jgYLjgovlpInmlbDjgpLjgZ3jga7jgb7jgb7plqLmlbDjgavmuKHjgZfjgabjgoLjgYTjgYTj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