std::is_convertible template in C++ with Examples
Last Updated :
12 Jun, 2020
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:
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;
class A {
};
class B : public A {
};
class C {
};
int main()
{
cout << boolalpha;
bool BtoA = is_convertible<B*, A*>::value;
cout << BtoA << endl;
bool AtoB = is_convertible<A*, B*>::value;
cout << AtoB << endl;
bool BtoC = is_convertible<B*, C*>::value;
cout << BtoC << endl;
cout << "int to float: "
<< is_convertible< int , float >::value
<< endl;
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/
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...