gpt4 book ai didi

c++ - 为什么模板试图用 'int&' 而不是 'int' 实例化?

转载 作者:太空狗 更新时间:2023-10-29 23:53:31 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的函数,该函数将从一定范围内的用户输入中获取一个数字。

当实例化此函数时,我明确告诉它我希望它用 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 :

template<class T>
T getInput(T default_value = T(), T min = std::numeric_limits<T>::min(), T max = std::numeric_limits<T>::max());

没有理由为这些参数使用模板(除了它不起作用的事实)。

编辑:自std::numeric_limits<T>::min() 以来,您不能将这些参数用作模板值是一个函数,它的值在运行时是已知的,并且模板值参数必须在编译时绑定(bind)到一个值。这是有效的:

template<class T, T min = 0, T max = 5>
T getInput(T default_value);

因为 0 和 5 在编译期间是已知的。

关于c++ - 为什么模板试图用 'int&' 而不是 'int' 实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10583198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com