0
template<typename T, typename U = int>
struct A {};

template<typename T, typename U>
struct A<T*, U> {};

template<typename T, typename U>
struct A<T[], U> {};

int main()
{
    A<int*> m; // m: A<int*, int>
    A<int[]> n; // n: A<int[], int>

    return 0;
}

What's the difference between int[] and int* here as template arguments? Isn't int[] simply a pointer too?

1
  • 2
    Arrays are not pointers. Commented Oct 19, 2020 at 23:31

2 Answers 2

2

Isn't int[] simply a pointer too?

No, it simply isn't. Arrays are arrays and pointers are pointers. Arrays are not pointers and pointers are not arrays. int[] is an array.

There is a case where "array is pointer (and isn't an array)": In a function parameter delcaration, an array parameter will be adjusted to be a pointer to element of that array type. Such adjustment doesn't apply to other contexts. Template arguments are a separate context from function arguments and in that context the mentioned adjustment does not occur.

What's the difference between int[] and int* here as template arguments?

The difference is that in one case the type argument is an array, and in the other case the type argument is a pointer.

Sign up to request clarification or add additional context in comments.

Comments

0

As a matter of fact, these are different types. You can tell because these do different things:

const char* a = "hi";
const char[] b = "hi";

The first allocates a pointer on the stack (and the literal probably somewhere else), the second allocates the whole literal on the stack as an array. Therefore, although they are implicitly convertible into each other, they are different types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.