MST

星途 面试题库

面试题:C++函数模板非类型参数的基础使用限制考查

在C++函数模板中,非类型参数有一些使用限制。请指出以下代码中,哪些地方违反了非类型参数的使用限制,并说明原因。 ```cpp #include <iostream> // 函数模板声明 template <typename T, int size> void printArray(T arr[size]) { for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; } int main() { int arr1[5] = {1, 2, 3, 4, 5}; double arr2[3] = {1.1, 2.2, 3.3}; // 调用函数模板 printArray<int, 5>(arr1); printArray<double, 3>(arr2); return 0; } ```
22.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

这段代码没有违反非类型参数的使用限制。

非类型参数的常见限制如下:

  1. 必须是常量表达式:在代码中,int size 作为非类型参数,在函数模板实例化时传入的是常量值(如 53),满足常量表达式要求。
  2. 类型限制:非类型参数的类型通常限于算术类型、枚举类型、指针类型或引用类型。这里 int 属于算术类型,符合要求。

综上,该代码在使用非类型参数方面不存在问题。