3 回答

TA貢獻1942條經驗 獲得超3個贊
是的,它是非類型參數。您可以有幾種模板參數
類型參數。
種類
模板(僅類和別名模板,無函數或變量模板)
非類型參數
指針
參考文獻
整數常量表達式
您所擁有的是最后一種。它是一個編譯時常量(所謂的常量表達式),類型為整數或枚舉。在標準中查找之后,我不得不將類模板移到“類型”部分中-即使模板不是類型。但是出于描述這些種類的目的,它們被稱為類型參數。您可以擁有具有外部鏈接的對象/函數的指針(以及成員指針)和引用(可以從其他對象文件鏈接到這些對象/函數,并且其地址在整個程序中是唯一的)。例子:
模板類型參數:
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
};

TA貢獻1797條經驗 獲得超6個贊
您基于“ unsigned int”對類進行模板化。
例:
template <unsigned int N>
class MyArray
{
public:
private:
double data[N]; // Use N as the size of the array
};
int main()
{
MyArray<2> a1;
MyArray<2> a2;
MyArray<4> b1;
a1 = a2; // OK The arrays are the same size.
a1 = b1; // FAIL because the size of the array is part of the
// template and thus the type, a1 and b1 are different types.
// Thus this is a COMPILE time failure.
}

TA貢獻1812條經驗 獲得超5個贊
完全有可能在一個整數而不是一個類型上模板化一個類。我們可以將模板化的值分配給變量,或者以其他整數形式使用的方式對其進行操作:
unsigned int x = N;
實際上,我們可以創建在編譯時評估的算法(來自Wikipedia):
template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0>
{
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
- 3 回答
- 0 關注
- 1721 瀏覽
添加回答
舉報