我正在尝试编写一个简单的函数,它将从用户输入中获取一个范围内的数字。
当实例化这个函数时,我明确告诉它我希望它实例化,int
但我仍然得到错误:
thermo.cpp:105:31: error: no matching function for call to ‘getInput(int&)’
为什么要试图找到一个int&
作为参数的函数?
template<class T, T min = std::numeric_limits<T>::min, T max = std::numeric_limits<T>::max>
T getInput(T default_value = T()){
std::string input;
T myNumber = T(); //default inits
while(true){
getline(cin, input);
if(input.length() == 0){
return default_value;
}
// This code converts from string to number safely.
stringstream myStream(input);
if (myStream >> myNumber){
if(myNumber > max || myNumber < min){
stringstream ss;
ss << "Input out of bounds. Received " << myNumber << " expected between " << min << " and " << max << ".";
throw invalid_argument(ss.str());
}
return myNumber;
}
cout << "Invalid number, please try again" << endl;
}
}
void get(const std::string& prompt, int& param){
cout << prompt << " [" << param << "]:";
param = getInput<int,0>(param); // i specifically tell it i want 'int', why am i getting 'int&'?
}
更新
如果我尝试 CharlesB 的建议:
void get(const std::string& prompt, int& param){
cout << prompt << " [" << param << "]:";
param = getInput<int,0>(int(param));
}
我明白了
thermo.cpp:105:36: 错误:没有匹配函数调用'getInput(int)'</p>
忘记:
cygwin下的g++ 4.5.3
命令行:
$ g++ thermo.cpp -o thermo.exe -Wall -pedantic -std=c++0x
更新 2
如果我这样称呼它
void get(const std::string& prompt, int& param){
cout << prompt << " [" << param << "]:";
param = getInput<int,0,15>(int(param)); // fully parameterized
}
numeric_limits
它有效......但我宁愿不在每次调用中指定上限(甚至不指定)。