is_convertible

Applicability

Product

Supported

Atlas A3 training products/Atlas A3 inference products

Atlas A2 training products/Atlas A2 inference products

Atlas 200I/500 A2 inference products

x

Atlas inference product's AI Core

x

Atlas inference product's Vector Core

x

Atlas training products

x

Function

Provides a mechanism for checking type conversion during program building as a type conversion check tool defined in the <type_traits> header file. This tool determines whether implicit conversion can be performed between two types and returns a Boolean value. This API can be used in template metaprogramming, function overload resolution, and static assertion to capture potential type conversion errors during program building and prevent runtime errors.

Prototype

1
2
template <typename From, typename To>
struct is_convertible;

Parameters

Table 1 Template parameters

Parameter

Description

From

Source type, that is, original type to be converted

To

Target type, that is, type to be converted to

Restrictions

The source type and target type do not support abstract classes or polymorphic types.

Returns

The static constant member value of is_convertible is used to obtain the returned Boolean value. The values of is_convertible<From, To>::value are as follows:

  • true: An object of the From type can be implicitly converted to the To type.
  • false: An object of the From type cannot be implicitly converted to the To type.

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Base {};
class Derived : public Base {};
class Unrelated {};

// Check whether int can be implicitly converted to double.
AscendC::PRINTF("Is int convertible to double? %d\n", AscendC::Std::is_convertible<int, double>::value);

// Check whether double can be implicitly converted to int.
AscendC::PRINTF("Is double convertible to int? %d\n", AscendC::Std::is_convertible<double, int>::value);

// Check whether Derived can be converted to Base.
AscendC::PRINTF("Is Derived callable with Base? %d\n", AscendC::Std::is_convertible<Derived, Base>::value);
// Check whether Base can be converted to Derived.
AscendC::PRINTF("Is Base callable with Derived? %d\n", AscendC::Std::is_convertible<Base, Derived>::value);
// Check whether Derived can be converted to Unrelated.
AscendC::PRINTF("Is Derived callable with Unrelated? %d\n", AscendC::Std::is_convertible<Derived, Unrelated>::value);
1
2
3
4
5
6
// Execution result:
Is int convertible to double? 1
Is double convertible to int? 1
Is Derived callable with Base? 1
Is Base callable with Derived? 0
Is Derived callable with Unrelated? 0