Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Template is_arithmetic trong C++ STL

std::is_arithmetic (header <type_traits>) kiểm tra xem kiểu T có phải là kiểu số học (arithmetic type) hay không. Kiểu số học bao gồm:

  • Integral types (kiểu nguyên): bool, char, signed char, unsigned char, char16_t, char32_t, wchar_t, short, int, long, long long (và các biến thể signed/unsigned).
  • Floating-point types (kiểu thực): float, double, long double.

KHÔNG phải arithmetic: class, struct, union, enum, pointer, reference, array, function, void.

Cú pháp

template <class T> struct is_arithmetic;

Ví dụ kiểm tra

#include <iostream>
#include <type_traits>
using namespace std;

class TP { };

int main() {
    cout << boolalpha;
    cout << "Kiểm tra is_arithmetic:\n";
    
    // Integral types
    cout << "bool:       " << is_arithmetic<bool>::value << '\n';       // true
    cout << "char:      " << is_arithmetic<char>::value << '\n';       // true
    cout << "short:     " << is_arithmetic<short>::value << '\n';     // true
    cout << "int:       " << is_arithmetic<int>::value << '\n';       // true
    cout << "long:      " << is_arithmetic<long>::value << '\n';       // true
    cout << "long long: " << is_arithmetic<long long>::value << '\n'; // true
    
    // Floating-point
    cout << "float:     " << is_arithmetic<float>::value << '\n';       // true
    cout << "double:    " << is_arithmetic<double>::value << '\n';       // true
    cout << "long double:" << is_arithmetic<long double>::value << '\n'; // true
    
    // KHÔNG phải arithmetic
    cout << "TP (class):   " << is_arithmetic<TP>::value << '\n';       // false
    cout << "int*:        " << is_arithmetic<int*>::value << '\n';       // false (pointer)
    cout << "int&:        " << is_arithmetic<int&>::value << '\n';       // false (reference)
    cout << "int[10]:     " << is_arithmetic<int[10]>::value << '\n';     // false (array)
    cout << "void:        " << is_arithmetic<void>::value << '\n';       // false
    
    return 0;
}

Đầu ra

Kiểm tra is_arithmetic:
bool:       true
char:      true
short:     true
int:       true
long:      true
long long: true
float:     true
double:    true
long double: true
TP (class):   false
int*:        false
int&:        false
int[10]:     false
void:        false

Mối quan hệ

is_arithmetic ≡ is_integral || is_floating_point

Ứng dụng

  • Template constraints: chỉ cho phép kiểu số học (ví dụ: hàm toán học template).
  • SFINAE: enable_if_t<is_arithmetic_v<T>>.
  • Phân loại kiểu trong metaprogramming.
  • C++20 Concept: std::integral, std::floating_point (chuyển từ trait sang concept).

Lưu ý

  • enum và enum class KHÔNG phải arithmetic (dù chuyển ngầm sang int).
  • Con trỏ (T*) KHÔNG phải arithmetic.
  • Kiểu người dùng (class/struct) KHÔNG bao giờ là arithmetic.