The std::is_convertible template of C++ STL is present in the <type_traits> header file. The std::is_convertible template of C++ STL is used to check whether any data type A is implicitly convertible to any data type B. It returns the boolean value either true or false.
Header File:
#include<type_traits>
Template Class:
template< class From, class To > struct is_convertible; template< class From, class To > struct is_nothrow_convertible;
Syntax:
is_convertible <A*, B*>::value;
Parameters: It takes two data type of A and B as:
- A: It represents the parameter to be converted.
- B: It represents the parameter in which parameter A is implicitly converted.
Return Value:
- True: If a given data type A is converted into data type B.
- False: If a given data type A is not converted into data type B.
Below is the program to demonstrate std::is_convertible in C++:
Program:
// C++ program to illustrate // std::is_convertible example #include <bits/stdc++.h> #include <type_traits> using namespace std;
// Given classes class A {
}; class B : public A {
}; class C {
}; // Driver Code int main()
{ cout << boolalpha;
// Check if class B is
// convertible to A or not
bool BtoA = is_convertible<B*, A*>::value;
cout << BtoA << endl;
// Check if class A is
// convertible to B or not
bool AtoB = is_convertible<A*, B*>::value;
cout << AtoB << endl;
// Check if class B is
// convertible to C or not
bool BtoC = is_convertible<B*, C*>::value;
cout << BtoC << endl;
// Check if int is convertible
// to float or not
cout << "int to float: "
<< is_convertible< int , float >::value
<< endl;
// Check if int is convertible
// to const int or not
cout << "int to const int: "
<< is_convertible< int , const int >::value
<< endl;
return 0;
} |
Output:
true false false int to float: true int to const int: true
Reference: http://www.cplusplus.com/reference/type_traits/is_convertible/
Article Tags :