Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference to an element of a std::tuple?

You can get the value of the nth element of an std::tuple using std::get<n>(tuple). But I need to pass one element of that tuple as reference to a function.

How do I get the reference to an element of a std::tuple?

like image 333
danijar Avatar asked Apr 05 '13 13:04

danijar


Video Answer


2 Answers

std::get returns a reference(either const or non-const), so this works:

void fun(int &a) {
    a = 15;
}

void test() {
    std::tuple<int, char> foo{ 12, 'a' };
    fun(std::get<0>(foo));
}

Demo here.

like image 104
mfontanini Avatar answered Oct 19 '22 13:10

mfontanini


get returns a reference, rvalue reference or const reference depending on the type of its argument.

like image 24
ecatmur Avatar answered Oct 19 '22 11:10

ecatmur