次のコードを考えてみましょう:
#include <iostream>
#include <functional>
int xx = 7;
template<class T>
void f1(T arg)
{
arg += xx;
}
template<class T>
void f2(T arg)
{
arg = xx;
}
int main()
{
int j;
j=100;
f1(std::ref(j));
std::cout << j << std::endl;
j=100;
f2(std::ref(j));
std::cout << j << std::endl;
}
このコードを実行すると、
107
100
2 番目の値は 100 ではなく 7 になるはずです。
何が足りないのでしょうか?
ベストアンサー1
f2
ヒントとなる小さな変更:
template<class T>
void f2(T arg)
{
arg.get() = xx;
}
これで期待どおりの動作が実現します。
std::ref
これは、オブジェクトを返すために発生しますstd::reference_wrapper<>
。再バインドラッパー。(参照http://en.cppreference.com/w/cpp/utility/ functional/reference_wrapper/operator%3D より)
ラップされた参照への割り当ては行われません。
この場合、 a がへの変換演算子を提供し、それがsの暗黙的な右側に暗黙的にバインドされるf1
ため、すべてが期待どおりに動作します。std::reference_wrapper<T>
T&
int
operator+