面试题答案
一键面试在C++函数模板中,非类型参数常见的数据类型有:
- 整型:包括
int
、char
、short
、long
、long long
等。例如:
template <int N>
int arraySize() {
return N;
}
限制:非类型参数的值在编译期必须是常量表达式。
- 指针类型:可以是对象指针或函数指针。例如:
template <int* ptr>
void printPtrValue() {
std::cout << *ptr << std::endl;
}
限制:指针所指向的对象必须具有静态存储期,即全局变量、静态局部变量等。
- 引用类型:对象引用或函数引用。例如:
template <int& ref>
void printRefValue() {
std::cout << ref << std::endl;
}
限制:引用的对象必须具有静态存储期。
- 枚举类型:例如:
enum class Color { Red, Green, Blue };
template <Color c>
void printColor() {
if (c == Color::Red) {
std::cout << "Red" << std::endl;
}
}
限制:同样要求在编译期是常量表达式。