is_same
Applicability
Product |
Supported |
|---|---|
√ |
|
√ |
|
x |
|
x |
|
x |
|
x |
Function
Determines whether two types are the same during program building as a type characteristics tool defined in the <type_traits> header file. This API applies to template metaprogramming, type check, and conditional building. It is used to determine type information at the building stage to prevent type mismatch at runtime.
Prototype
1 2 | template <typename Tp, typename Up> struct is_same; |
Parameters
Parameter |
Description |
|---|---|
Tp |
First type to be compared to check whether two types are the same. |
Up |
Second type to be compared to check whether two types are the same. |
Restrictions
None
Returns
The static constant member value of is_same is used to obtain the returned Boolean value. The values of is_same<Tp, Up>::value are as follows:
- true: Tp and Up are the same type.
- false: Tp and Up are not the same type.
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 | // Define two different classes. class ClassA {}; class ClassB {}; // Define the same class twice. class ClassC {}; using ClassC_alias = ClassC; // Define a simple template class. template <typename T> class TemplateClass {}; // Compare the same basic type. AscendC::PRINTF("Is int the same as int? %d\n", AscendC::Std::is_same<int, int>::value); // Compare different basic types. AscendC::PRINTF("Is int the same as double? %d\n", AscendC::Std::is_same<int, double>::value); // Compare different class types. AscendC::PRINTF("Is ClassA the same as ClassB? %d\n", AscendC::Std::is_same<ClassA, ClassB>::value); // Compare the same class type. AscendC::PRINTF("Is ClassC the same as ClassC_alias? %d\n", AscendC::Std::is_same<ClassC, ClassC_alias>::value); // Compare the same template instantiation type. AscendC::PRINTF("Is TemplateClass<int> the same as TemplateClass<int>? %d\n", AscendC::Std::is_same<TemplateClass<int>, TemplateClass<int>>::value); // Compare different template instantiation types. AscendC::PRINTF("Is TemplateClass<int> the same as TemplateClass<double>? %d\n", AscendC::Std::is_same<TemplateClass<int>, TemplateClass<double>>::value); |
1 2 3 4 5 6 7 | // Execution result: Is int the same as int? 1 Is int the same as double? 0 Is ClassA the same as ClassB? 0 Is ClassC the same as ClassC_alias? 1 Is TemplateClass<int> the same as TemplateClass<int>? 1 Is TemplateClass<int> the same as TemplateClass<double>? 0 |