简体   繁体   English

(&) - 括号中的&符号 - 在此代码中是什么意思?

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

In this answer , the following code is given (C++11): 这个答案中 ,给出了以下代码(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. 在函数中,你实际上并不需要变量的名称 ,只需要N上的模板推导 - 所以我们可以简单地选择省略它。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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