Rishabh Gupta
Rishabh Gupta

Reputation: 67

Return type and argument type confusion in template

In this code, both return type and argument type of template is 'T' and I have returned boolean. And in argument, integer/float is passed. But my code is running successfully. How is that possible?

#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;
}

Upvotes: 0

Views: 72

Answers (1)

user15401571
user15401571

Reputation:

bool is implicitly convertible to int, which in turn is convertible (implicitly) to a float, double, etc.

True is convertible to 1, while false is convertible to 0.

To prove that this is the case, change the int type of n and the int[] type of arr to std::string and std::string[], respectively. For me, this is what the compiler shows:

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 ==========

The compiler is actually pretty smart, and figures out that T must be convertible to bool, and therefore it fails to compile, as std::string is not convertible to bool.

Upvotes: 2

Related Questions