gpt4 book ai didi

c++ - 模板 是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 11:53:23 26 4
gpt4 key购买 nike

在声明模板时,我习惯了这种代码:

template <class T>

但是in this question ,他们使用:

template <unsigned int N>

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

最佳答案

是的,它是一个非类型参数。你可以有几种模板参数

  • 类型参数。
    • 类型
    • 模板(只有类和别名模板,没有函数或变量模板)
  • 非类型参数
    • 指针
    • 引用文献
    • 整型常量表达式

你所拥有的是最后一种。它是一个编译时常量(所谓的常量表达式),并且是整数或枚举类型。在标准中查找后,我不得不将类模板上移到类型部分——即使模板不是类型。但是为了描述这些类型,它们被称为类型参数。您可以拥有指针(以及成员指针)和对具有外部链接的对象/函数的引用(可以从其他目标文件链接到并且其地址在整个程序中是唯一的)。例子:

模板类型参数:

template<typename T>
struct Container {
T t;
};

// pass type "long" as argument.
Container<long> test;

模板整数参数:

template<unsigned int S>
struct Vector {
unsigned char bytes[S];
};

// pass 3 as argument.
Vector<3> test;

模板指针参数(将指针传递给函数)

template<void (*F)()>
struct FunctionWrapper {
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 {
static void do_it() { A = 10; }
};

// pass flag as argument
int flag;
SillyExample<flag> test;

模板模板参数。

template<template<typename T> class AllocatePolicy>
struct Pool {
void allocate(size_t n) {
int *p = AllocatePolicy<int>::allocate(n);
}
};

// pass the template "allocator" as argument.
template<typename T>
struct allocator { static T * allocate(size_t n) { return 0; } };
Pool<allocator> test;

没有任何参数的模板是不可能的。但是没有任何显式参数的模板是可能的 - 它具有默认参数:

template<unsigned int SIZE = 3>
struct Vector {
unsigned char buffer[SIZE];
};

Vector<> test;

在语法上,template<>保留用于标记显式模板特化,而不是没有参数的模板:

template<>
struct Vector<3> {
// alternative definition for SIZE == 3
};

关于c++ - 模板 <unsigned int N> 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/499106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com