Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deducing a tuple's types

I have code something like this:

template <typename T>
inline typename ::std::enable_if<
  is_std_tuple<T>{},
  T
>::type
get()
{
  // pull tuple's elements from somewhere
}

In order to deduce the template type parameters the tuple was instantiated with, I did this casting:

static_cast<T*>(nullptr)

and pass this as a parameter to a function

template <typename ...A>
void deduce_tuple(::std::tuple<A...>* const);

Am I committing UB? Is there a better way?

like image 924
user1095108 Avatar asked Mar 16 '16 10:03

user1095108


People also ask

Can a tuple have more than 2 elements?

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). A tuple can also be created without using parentheses.

What is Make_tuple?

std::make_tupleCreates a tuple object, deducing the target type from the types of arguments. For each Ti in Types... , the corresponding type Vi in VTypes... is std::decay<Ti>::type unless application of std::decay results in std::reference_wrapper<X> for some type X , in which case the deduced type is X& .


1 Answers

The imperfection here is that we cannot partially specialize function templates. Your way is fine, since we're not dereferencing the null pointer; I'd prefer using a designated tag:

template <typename...> struct deduction_tag {};

template <typename... Ts>
std::tuple<Ts...> get(deduction_tag<std::tuple<Ts...>>) {
    // […]
}
template <typename T>
std::enable_if_t<is_std_tuple<T>{}, T> get() {
    return get(deduction_tag<T>{});
}
like image 116
Columbo Avatar answered Sep 30 '22 15:09

Columbo