简体   繁体   中英

What does (&) — ampersand in parentheses — mean in this code?

In this answer , the following code is given (C++11):

template <typename T, size_t N>
constexpr size_t size_of(T (&)[N]) {
    return N;
}

What does the (&) mean in this context? This sort of thing is exceptionally difficult to search for.

It's shorthand for something like this:

template <typename T, size_t N>
constexpr size_t size_of(T (&anonymous_variable)[N]) {
    return N;
}

In the function, you don't actually need the name of the variable, just the template deduction on N - so we can simply choose to omit it. The parentheses are syntactically necessary in order to pass the array in by reference - you can't pass in an array by value.

This is passing an array as a parameter by reference:

template <typename T, size_t N>
constexpr size_t size_of(T (&)[N]) {
    return N;
}

As you cannot pass an array like this:

template <typename T, size_t N>
constexpr size_t size_of(T[N]) {
    return N;
}

If the array was given a name, it would look like:

template <typename T, size_t N>
constexpr size_t size_of(T (&arrayname)[N]) {
    return N;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM