Detecting the reference types in a tuple

147 views Asked by At

I learned about std::forward_as_tuple. I use this tech in my project:

template<class... Ts>
tuple<Ts&&...> values(Ts&&... ts) // yes, values is renamed forward_as_tupe
{
    return tuple<Ts&&...>(std::forward<Ts>(ts)...)
}

class C_SQL { ...... }; // MySQL C API, SQL statement encapsulation
                        // operator% is well defined.

char pszname[32];
int  iage;

C_SQL sql;
sql % "insert into student (name,age,grade)"
    %  values(pszname, iage, 2 );

Then, I can get a MySQL C API Prepared Statement string like this:

"insert into student (name,age,grade) values(?, ?, 2 )"

"pszname" and "iage" are lvalues, so they are binding variables. 2 is an rvalue, so I can tell that it's a literal in an SQL statement.

My question is:

How can I tell if an element in a tuple is an rvalue or an lvalue?

For example:

int k;
tuple<int&, int&&> t = forward_as_tuple(k, 2);

The first element is an lvalue-reference, the second is an rvalue-reference.

Please use C++ code to tell that. The code can deal with varaidic template tuple.

2

There are 2 answers

0
rodrigo On BEST ANSWER

You have a lot of useful traits in #include <type_traits>. You are probably interested in std::is_rvalue_reference and std::is_lvalue_reference.

For example, to check if the first type is an rvalue:

bool r0 = std::is_rvalue_reference<std::tuple_element<0, decltype(t)>::type>::value;
0
Jarod42 On

you may use

std::is_rvalue_reference<std::tuple_element<Index, MyTuple>::type>::value
std::is_lvalue_reference<std::tuple_element<Index, MyTuple>::type>::value