我想寫一個簡單的函數,將從一個範圍內的用戶輸入給我一個數字。爲什麼模板試圖用'int'而不是'int'實例化?
當instanciating這個功能我明確告訴它我想它實例化與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: error: no matching function for call to ‘getInput(int)’
忘記:
g++ 4.5.3 under cygwin
命令行:
$ 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
)。
是的,那也來到我身邊。但接下來的另一個問題是:爲什麼'min'和'max'制動功能的查找... – RedX
你去了哪裏,編輯了我的答案。 – mfontanini
是的,就是這樣...誰決定做這些功能,而不是常量... – RedX