C++ std::is_convertible模板用法及代码示例

<type_traits>头文件中提供了C++ STL的std::is_convertible模板。 C++ STL的std::is_convertible模板用于检查是否可以将任何数据类型A隐式转换为任何数据类型B。它返回布尔值true或false。

头文件:

#include<type_traits>

模板类别:

template< class From, class To >
struct is_convertible;

template< class From, class To >
struct is_nothrow_convertible;

用法:

is_convertible <A*, B*>::value;

参数:它采用A和B两种数据类型:

  • A:它代表要转换的参数。
  • B:它代表参数A隐式转换的参数。

返回值:

  • True:如果将给定的数据类型A转换为数据类型B。
  • False:如果给定的数据类型A没有转换为数据类型B。

下面是演示C++中std::is_convertible的程序:

程序:

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

输出:

true
false
false
int to float:true
int to const int:true

参考:http://www.cplusplus.com/reference/type_traits/is_convertible/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值