模板中的返回类型和参数类型混淆

时间:2021-06-20 21:25:59

标签: c++ templates

在这段代码中,模板的返回类型和参数类型都是“T”,我返回的是布尔值。在参数中,传递整数/浮点数。但是我的代码运行成功。这怎么可能?

#include <iostream>
using namespace std;
template<class T>
T SearchInArray(T x[], T element) {
   int j;
   for(j=0;j<5;j++){
       if(element==x[j])
       {return true;
       break;}
   }
   return false;
}

int main() {int i;
cout<<"Enter 5 integer numbers"<<endl;
int arr[5];
for(i=0;i<5;i++){
    cin>>arr[i];
}
int n;
cout<<"Enter element to search: ";
cin>>n;
if(SearchInArray(arr,n))
cout<<"Element "<<n<<" is found"<<endl<<endl;
else
cout<<"Element "<<n<<" is not found"<<endl<<endl;
cout<<"Enter 5 float numbers"<<endl;
float arr1[5];
for(i=0;i<5;i++){
    cin>>arr1[i];
}
float n1;
cout<<"Enter element to search: ";
cin>>n1;
if(SearchInArray(arr1,n1))
cout<<"Element "<<n1<<" is found"<<endl<<endl;
else
cout<<"Element "<<n1<<" is not found"<<endl<<endl;
    return 0;
}

1 个答案:

答案 0 :(得分:2)

bool 可隐式转换为 int,而后者又可(隐式)转换为 floatdouble 等。

True 可转换为 1,而 false 可转换为 0

为了证明是这样,将int的{​​{1}}类型和n的{​​{1}}类型改为int[]和{{1} }, 分别。对我来说,这就是编译器显示的内容:

arr

编译器实际上非常聪明,并且发现 std::string 必须可以转换为 bool,因此编译失败,因为 std::string[] 不能转换为 Build started... 1>------ Build started: Project: Stack Overflow, Configuration: Debug Win32 ------ 1>Source.cpp 1>C:\dev\Stack Overflow\Source.cpp(534,27): error C2451: a conditional expression of type 'T' is not valid 1> with 1> [ 1> T=std::string 1> ] 1>C:\dev\Stack Overflow\Source.cpp(534,19): message : No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called 1>Done building project "Stack Overflow.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

相关问题