Use type traits to detect whether an array (or a pointer) was passed

Viewed 75

I am trying to get a simple example to work to understand how to use std::enable_if, here is the problem:

I am reading the textbook C++ Templates The Complete Guide by David Vandevoorde, Nicolai M.Josuttis, Chapter 7, Section 4.

This chapter mentions: "You can use type traits to detect whether an array (or a pointer) was passed", and its following code:

template<typename T,
         std::enable_if_t<std::is_array_v<T>>>
void foo(T&& arg1, T&& arg2)
{
    
}

My question is, how should the above code be called and used? for example, I tried:

int x[] = {1, 2, 3};
int y[] = {1, 2, 3, 4, 5};
foo(x, y);

but didn't compile, i couldn't find similar usage online, can someone please give me some hints or code guidance on how to use above code?

1 Answers
  1. You should specify a default value for the 2nd template parameter, or move it to the return type.

  2. With forwarding reference T might be deduced as lvalue-reference (when passed lvalues like x and y), which is not an array and yields false for std::is_array.

  3. x is of type int[3], y is of type int[5]. They're different types and causes the type deduction on T failing.

So

template<typename T,
         std::enable_if_t<std::is_array_v<std::remove_reference_t<T>>>* = nullptr>
void foo(T&& arg1, T&& arg2)
{ 
}

or

template<typename T>
std::enable_if_t<std::is_array_v<std::remove_reference_t<T>>> foo(T&& arg1, T&& arg2)
{ 
}

then

int x[] = {1, 2, 3};
int y[] = {4, 5, 6};
foo(x, y);

LIVE

Related