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

2020-03-14 22:32发布

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?

3条回答
Fickle 薄情
2楼-- · 2020-03-14 23:01

std::get returns a reference to the element at the specified position in the tuple.

http://www.cplusplus.com/reference/tuple/get/

查看更多
爷、活的狠高调
3楼-- · 2020-03-14 23:03

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.

查看更多
ら.Afraid
4楼-- · 2020-03-14 23:11

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

查看更多
登录 后发表回答