2012-02-01 22 views
6

Mam następujący kod:Jak przekazać referencję za pośrednictwem pakietu parametrów?

#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); 
} 

Obecnie drukuje 1000, czyli nowa wartość b ginie gdzieś. Domyślam się, że to dlatego, że foo przekazuje parametry w pakiecie parametrów według wartości. Jak mogę to naprawić?

Odpowiedz

5

Korzystając odniesienie:

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

To nie powieść, jeśli 'A' jest rvalue, mimo że powinny być semantycznie dopuszczalne. '&&' byłoby lepiej, myślę. – ildjarn

+0

@ildjarn masz rację. naprawiono kod –

+0

Idealnie pasuje do moich potrzeb, jeśli użyto '&&'. – p12

7

tak:

#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; 
} 
Powiązane problemy