C++ 模板语法:template<int T> 详解
template
使用 template
template<int T>
class Square {
public:
static const int value = T * T;
};
在这个例子中,模板参数 T 表示要计算平方的整数。Square 类中的静态成员变量 value 用于存储计算结果。使用时,可以通过实例化 Square 类来计算不同整数的平方:
Square<2>::value // 返回 4
Square<3>::value // 返回 9
Square<4>::value // 返回 16
此外,template
template<int T>
int add(int x) {
return x + T;
}
在这个例子中,模板参数 T 表示要加的整数。add 函数用于将参数 x 加上 T,并返回结果。使用时,可以通过指定模板参数来调用 add 函数:
add<2>(3) // 返回 5
add<3>(3) // 返回 6
add<4>(3) // 返回 7
总之,template
原文地址: https://www.cveoy.top/t/topic/kWbe 著作权归作者所有。请勿转载和采集!