猿问

模板<unsigned int N>是什么意思?

在声明模板时,我习惯于使用这种代码:


template <class T>

但是在这个问题上,他们使用了:


template <unsigned int N>

我检查它是否可以编译。但是这是什么意思?它是非类型参数吗?如果是这样,我们如何有一个没有任何类型参数的模板?


侃侃尔雅
浏览 1688回答 3
3回答

手掌心

是的,它是非类型参数。您可以有几种模板参数类型参数。种类模板(仅类和别名模板,无函数或变量模板)非类型参数指针参考文献整数常量表达式您所拥有的是最后一种。它是一个编译时常量(所谓的常量表达式),类型为整数或枚举。在标准中查找之后,我不得不将类模板移到“类型”部分中-即使模板不是类型。但是出于描述这些种类的目的,它们被称为类型参数。您可以拥有具有外部链接的对象/函数的指针(以及成员指针)和引用(可以从其他对象文件链接到这些对象/函数,并且其地址在整个程序中是唯一的)。例子:模板类型参数:template<typename T>struct Container {&nbsp; &nbsp; T t;};// pass type "long" as argument.Container<long> test;模板整数参数:template<unsigned int S>struct Vector {&nbsp; &nbsp; unsigned char bytes[S];};// pass 3 as argument.Vector<3> test;模板指针参数(将指针传递给函数)template<void (*F)()>struct FunctionWrapper {&nbsp; &nbsp; static void call_it() { F(); }};// pass address of function do_it as argument.void do_it() { }FunctionWrapper<&do_it> test;模板参考参数(传递整数)template<int &A>struct SillyExample {&nbsp; &nbsp; static void do_it() { A = 10; }};// pass flag as argumentint flag;SillyExample<flag> test;模板模板参数。template<template<typename T> class AllocatePolicy>struct Pool {&nbsp; &nbsp; void allocate(size_t n) {&nbsp; &nbsp; &nbsp; &nbsp; int *p = AllocatePolicy<int>::allocate(n);&nbsp; &nbsp; }};// pass the template "allocator" as argument.&nbsp;template<typename T>struct allocator { static T * allocate(size_t n) { return 0; } };Pool<allocator> test;没有任何参数的模板是不可能的。但是没有任何显式参数的模板也是可能的-它具有默认参数:template<unsigned int SIZE = 3>struct Vector {&nbsp; &nbsp; unsigned char buffer[SIZE];};Vector<> test;从语法上讲,template<>保留标记专用的显式模板,而不是不带参数的模板:template<>struct Vector<3> {&nbsp; &nbsp; // alternative definition for SIZE == 3};

FFIVE

您基于“ unsigned int”对类进行模板化。例:template <unsigned int N>class MyArray{&nbsp; &nbsp; public:&nbsp; &nbsp; private:&nbsp; &nbsp; &nbsp; &nbsp; double&nbsp; &nbsp; data[N]; // Use N as the size of the array};int main(){&nbsp; &nbsp; MyArray<2>&nbsp; &nbsp; &nbsp;a1;&nbsp; &nbsp; MyArray<2>&nbsp; &nbsp; &nbsp;a2;&nbsp; &nbsp; MyArray<4>&nbsp; &nbsp; &nbsp;b1;&nbsp; &nbsp; a1 = a2;&nbsp; // OK The arrays are the same size.&nbsp; &nbsp; a1 = b1;&nbsp; // FAIL because the size of the array is part of the&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; template and thus the type, a1 and b1 are different types.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //&nbsp; &nbsp; &nbsp; Thus this is a COMPILE time failure.&nbsp;}

慕雪6442864

完全有可能在一个整数而不是一个类型上模板化一个类。我们可以将模板化的值分配给变量,或者以其他整数形式使用的方式对其进行操作:unsigned int x = N;实际上,我们可以创建在编译时评估的算法(来自Wikipedia):template <int N>struct Factorial&nbsp;{&nbsp; &nbsp; &nbsp;enum { value = N * Factorial<N - 1>::value };};template <>struct Factorial<0>&nbsp;{&nbsp; &nbsp; enum { value = 1 };};// Factorial<4>::value == 24// Factorial<0>::value == 1void foo(){&nbsp; &nbsp; int x = Factorial<4>::value; // == 24&nbsp; &nbsp; int y = Factorial<0>::value; // == 1}
随时随地看视频慕课网APP
我要回答