我正在尝试将字符串流从文件传递到函数.当我调用模板函数时,我收到一个错误:没有匹配函数来调用'toFile'.我验证了生命是打开的,数据已从它传递到stringstream.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
template <typename T1>
void toFile(string type, int NumOfElements, stringstream& ss){
T1* myArray = new T1[NumOfElements]; // declaring new array to store the elements
int value;
for(int i = 0; i < NumOfElements; i++){ // store the elements in the array
ss >> value;
myArray[i] = value;
cout << myArray[i] << " ";
}
}
int main(int argc, char *argv[])
{
ifstream ins;
ofstream outs;
string strg1;
string type;
int NumOfElements = 0;
stringstream inputString;
ins.open(argv[1]);
if(argc<1) {
cout << "please provide the file path." << endl;
exit(1);
}
while (getline(ins, strg1)){ // reading line from the file
inputString.clear(); // clearing the inputString before reading a new line
inputString << strg1;
inputString >> type ; // reading 1st element in a row
inputString >> NumOfElements; // reading 2nd element in a row
toFile(type, NumOfElements, inputString);
}
ins.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
toFile是一个函数模板,因此只能使用模板参数调用它.有时候,函数模板可以从参数中推导出它们的参数,但由于T1你的参数列表中没有使用它们,所以无法推断它.您需要显式提供模板参数,例如:
toFile<int>(type, NumOfElements, inputString);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
254 次 |
| 最近记录: |