HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Test whether a type T is among the types of a tuple

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
amongthetypetupletesttypeswhether

Problem

On SO, I asked for a way to do it without variadics. I also provided a typical "normal" implementation with variadics:

template 
struct Is_in_tuple;

template 
struct Is_in_tuple  >
{
  static const bool value = Is_in_tuple >::value;
};

template 
struct Is_in_tuple  >
{
  static const bool value = true;
};

template 
struct Is_in_tuple  >
{
  static const bool value = false;
};


I'd like a review on the above code. Is it safe / OK / missing something, before I make it my standard way of querying type lists?

Solution

Since you're implementing a traits-like check, I would typically expect your traits class types to be derived from std::true_type and std::false_type. This is certainly not required, and overall this implementation doesn't bug me. I was slightly surprised to see std::tuple<> called out explicitly, but that doesn't seem to change the overall correctness in any way.

The biggest question I have is how exact you want your type matching to be. Do you require exact type matches like std::is_same or usably similar types like std::is_convertible? To be concrete, what should Is_in_tuple>::value be? It would be great to have some unit tests that document this sort of edge case.

The only thing I see wrong with your implementation is by implication: either you must have included some form of using, either using namespace std; or using std::tuple;, or you are dependent on someone else having done so before including this header. While correct use of using is fine, particularly in implementation files or inside functions, I would strongly suggest avoiding it here where it will pollute (or require previous pollution of) the compilation unit of whatever code includes this.

Context

StackExchange Code Review Q#51043, answer score: 7

Revisions (0)

No revisions yet.