1

I have come across the following stripped down code that passes an array into a constructor:

struct FF
{
    template <int N> FF(int(&a)[N]);
private:
    void* arena_;
};


template <int N>
inline FF::FF(int(&a)[N])
    : arena_(a)
{
    /*empty*/
}

This can be called as follows:

int intArr[5];
FF ff(intArr);

Now, in int(&a)[N], clearly the template argument N is going to be taken from the size of the array, 5 in this case, but I don't understand the int(&a) part. Whenever I have passed an array before, I have always passed it to a function expecting a pointer (since passing an array is the same as passing the address of the first element of that array, so we effectively assign &array to *). But here we seem to be passing the address of the array to a constructor expecting what looks like a reference?

I then added a second constructor:

FF(int* pArr) {}

Now, the templated constructor doesn't get called at all, this one does!

Can someone please explain this strange templated form of the constructor and what it is saying, and then why when I add a constructor taking a pointer, the templated version doesn't get called at all?

13
  • 4
    "int(&a)[N]" declares a as "lvalue reference to array of N int". Blame C. Commented Mar 17, 2017 at 19:47
  • 1
    Arrays are not pointers. They decay to pointers at the drop of a hat, but until that hat drops they are still arrays. Commented Mar 17, 2017 at 19:53
  • 1
    @Wad, that is correct. Commented Mar 17, 2017 at 19:56
  • 1
    Right. So that just leaves the question as to why my version taking the pointer is preferred over the templated version. Can someone please post an answer to that, along with the information already given that explains the "odd" syntax? Commented Mar 17, 2017 at 19:58
  • 1
    related: stackoverflow.com/questions/21972652/… Commented Mar 17, 2017 at 20:19

0

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.