所以我现在是一名学生并且已经进行了以下练习:编写一个在数组中打印元素的函数.数组通过参数发送到函数.如果此参数不是数组,则必须抛出类型invalid_argument的异常.在main()函数中测试函数.
所以我的代码目前如下:
#include <iostream>
#include <exception>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::invalid_argument;
using std::string;
template<class T>void printArray(T arr){
try{
arr.size();
}
catch(...){
for (int i=0; i < sizeof(arr); i++){
cout << arr[i] << endl;
}
}
throw invalid_argument("Argument not of type array");
};
int main(){
string arrChars[5] = {"1", "2", "3", "John", "5"};
string s = "Jack";
try{
printArray(arrChars);
}
catch(invalid_argument &e){
cout << "Error: " << e.what() << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是在尝试了其他选项之后:
template<class …Run Code Online (Sandbox Code Playgroud)