尝试用C ++编写类似于python中的range的函数,采用各种类型的数值参数并返回用户指定类型的向量。不了解错误的根源。
如果将step_value设置为与返回向量的类型相同的typename T,则一切正常。但是,如果输出向量的类型名和step_value不同,我将继续收到以下描述的错误
template <typename T, typename T1, typename T2, typename T3>
vector <T> range(T1 end_value, T2 begin_value = 0, T3 step_value = 1)
{
vector <T> output_value(0);
T converted_begin_value = static_cast<T>(begin_value);
T converted_end_value = static_cast<T>(end_value);
T converted_step_value = static_cast<T>(step_value);
if (converted_step_value > 0)
{
if (converted_begin_value <= converted_end_value)
{
T current_value = converted_begin_value;
while (current_value <= converted_end_value)
{
output_value.push_back(current_value);
current_value += converted_step_value;
}
}
}
if (converted_step_value < 0)
{
if (converted_begin_value >= converted_end_value)
{
T current_value = converted_begin_value;
while (current_value >= converted_end_value)
{
output_value.push_back(current_value);
current_value += converted_step_value;
}
}
}
return output_value;
}`
int main(int argc, wchar_t* argv[])
{
vector <double> test = range(10,6,2);
vector <int> test2 = range(10,6,2);
}
主函数中的两行都给出相同的错误 错误C2672'范围':找不到匹配的重载函数 错误C2783'std :: vector <_Ty,std :: allocator <_Ty >> range(T1,T2,T3)':无法推断出'T'的模板参数
答案 0 :(得分:0)
我不太确定您遇到的错误是什么,但是它通过添加模板返回值的类型对我有用。除此之外,我没有任何错误,一切都可以立即解决。
看看是否可以像这样改变您的电源:
int main(int argc, wchar_t* argv[])
{
vector <double> test = range <double> (10,6,2);
vector <int> test2 = range <int> (10,6,2);
}
根据评论编辑:
C++ cannot deduce by return type
解释了为什么会起作用:+1: