2012-02-01 83 views
6

我有以下代碼:如何通過參數包傳遞參考?

#include <cstdio> 

template<class Fun, class... Args> 
void foo(Fun f, Args... args) 
{ 
    f(args...); 
} 

int main() 
{ 
    int a = 2; 
    int b = 1000; 

    foo([](int &b, int a){ b = a; }, b, a); 
    std::printf("%d\n", b); 
} 

目前它打印1000,也就是b新的價值得到某處丟失。我想這是因爲foo按值傳遞參數包中的參數。我該如何解決這個問題?

回答

5

通過使用參考:

template<class Fun, class... Args> 
void foo(Fun f, Args&&... args) 
{ 
    f(std::forward<Args>(args)...); 
} 
+3

如果'了'是一個右值,雖然這應該是語義上允許這將失敗。我認爲'&&'會更好。 – ildjarn 2012-02-01 21:24:21

+0

@ildjarn你是對的。修正了代碼 – 2012-02-01 21:32:01

+0

如果使用'&&'完全符合我的需求。 – p12 2012-02-01 21:34:44

7

這樣的:

#include <iostream> 
#include <functional> 

template<class Fun, class... Args> 
void foo(Fun f, Args... args) 
{ 
    f(args...); 
} 

int main() 
{ 
    int a = 2; 
    int b = 1000; 

    foo([](int &b, int a){ b = a; }, std::ref(b), a); 
    std::cout << b << std::endl; 
}