简体   繁体   English

具有多个类型名的C ++模板

[英]C++ templates with multiple typenames

I'm learning about a technique used to find the number of elements in an array (so that I can hopefully starting writing sorting algorithms without requiring the length of the array to be passed with the array as a parameter) but in the tutorial, this line appears as the template declaration: 我正在学习一种用于查找数组中元素数量的技术(以便希望可以开始编写排序算法,而无需将数组的长度作为参数传递给数组),但是在本教程中,行显示为模板声明:

template <typename T, size_t N>

I honestly didn't know you could declare multiple typenames in one template declaration, but furthermore what does "size_t N" do? 老实说,我不知道您可以在一个模板声明中声明多个类型名,但是“ size_t N”又做什么呢? is this a variable declaration inside of a template declaration as well? 这也是模板声明中的变量声明吗?

size_t is a type that resembles unsigned int . size_t是类似于unsigned int的类型。 Having it in the template parameter just means that you pass a size_t , not a type. 在template参数中包含它只是意味着您传递了size_t ,而不是类型。 N probably represents the size of an array, which is an unsigned value. N可能表示数组的大小,这是一个无符号值。 For example: 例如:

template<typename T, size_t N>
void zeroArray(T (&arr)[N]) {    //arr is a reference to an array 
    std::fill(arr, arr + N, 0);  //of N elements of type T
}

int main() {
    int arr[3];
    zeroArray<int, 3>(arr);
}

In the example, I could have said: 在示例中,我可以说:

zeroArray(arr);

because both template arguments are deduced. 因为两个模板参数都被推导。

what does "size_t N" do? “ size_t N”有什么作用? is this a variable declaration inside of a template declaration as well? 这也是模板声明中的变量声明吗?

Yep, basically. 是的,基本上。

Template arguments may be types or values of integer type. 模板参数可以是类型或整数类型的值。 There are a few other things they can be, too (see [C++11: 14.3.2/1] ) and I wouldn't call them "variables" per se , but... 它们也可以是其他一些东西(请参阅[C++11: 14.3.2/1] ),我不会将它们本身称为“变量”,但是...

Anyway, the values can be deduced just like types, too, so: 无论如何,这些值也可以像类型一样推导,因此:

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

int main()
{
   int  x[5];
   char y[10];
   std::string z[20];

   std::cout << array_size(x) << ',' << array_size(y) << ',' << array_size(z) << '\n';
}

Output: 5,10,20 . 输出: 5,10,20

Perfectly valid. 完全有效。

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

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