天天看點

C++11: std::forward

#include <utility>
#include <iostream>

template <typename F, typename T1, typename T2> 
void flip(F f, T1 &&t1, T2 &&t2)
{
        f(std::forward<T2>(t2), std::forward<T1>(t1));
}

void f(int v1, int &v2)
{
        std::cout << v1 << " " << ++v2 << std::endl;
}

void g(int &&i, int &j) 
{
        std::cout << i << " " << ++j << std::endl;
}

int main()
{
        int i = , j = ;
        f(, i);
        flip(f, i, );
        std::cout << "i = " << i << std::endl;

        flip(g, j, );
        std::cout << "j = " << j << std::endl;

        return ;
}
           
/// using std::forward to preserve type information in a call
// from C++ primer 5th(p.694)
// g++ xx.cpp -std=c++11
// gcc 4.9.2
           

繼續閱讀