conditional
Applicability
Product |
Supported |
|---|---|
√ |
|
√ |
|
x |
|
x |
|
x |
|
x |
Function
Selects a type from two types based on a Boolean condition during program building as a type characteristics tool defined in the <type_traits> header file. This API can be used in template metaprogramming to select a proper type based on different conditions, enhancing the universality and flexibility of code.
conditional has a nested type member whose value depends on the value of Bp. If Bp is set to true, the value of conditional<Bp, If, Then>::type is If. If Bp is set to false, the value of conditional<Bp, If, Then>::type is Then.
Prototype
1 2 | template <bool Bp, typename If, typename Then> struct conditional; |
Parameters
Parameter |
Description |
|---|---|
Bp |
A Boolean constant expression, which is used as the condition for selecting a type. |
If |
Type selected when Bp is set to true. |
Then |
Type selected when Bp is set to false. |
Restrictions
None
Returns
The static constant member type of conditional is used to obtain the return value. The values of conditional<Bp, If, Then>::type are as follows:
- If: Bp is set to true.
- Then: Bp is set to false.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | // Define two different types. struct TypeA { __aicore__ inline static void print() { AscendC::PRINTF("This is TypeA..\n"); } }; struct TypeB { __aicore__ inline static void print() { AscendC::PRINTF("This is TypeB..\n"); } }; // Select a type based on conditions. template <bool Condition> __aicore__ inline void selectType() { using SelectedType = typename AscendC::Std::conditional<Condition, TypeA, TypeB>::type; SelectedType::print(); } // Define a template function to select different types based on conditions. template <bool Condition> __aicore__ inline void selectOtherType() { using SelectedType = typename std::conditional<Condition, int, float>::type; if constexpr (std::is_same_v<SelectedType, int>) { AscendC::PRINTF("Selected type is int.\n"); } else { AscendC::PRINTF("Selected type is float.\n"); } } // If the condition is true, select TypeA. selectType<true>(); // If the condition is false, select TypeB. selectType<false>(); // Test when the condition is true. selectOtherType<true>(); // Test when the condition is false. selectOtherType<false>(); |
1 2 3 4 5 | // Execution result: This is TypeA.. This is TypeB.. Selected type is int. Selected type is float. |