example3_static_assertions.cpp

 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
#include <cassert>
#include <iostream>
#include <type_traits>

template <typename T>
class NumericOperations {
public:
    static_assert(std::is_arithmetic<T>::value, "T must be an arithmetic type");

    T add(T a, T b) {
        return a + b;
    }

    T subtract(T a, T b) {
        return a - b;
    }
};

int main() {
    NumericOperations<int> intOps;
    std::cout << "5 + 3 = " << intOps.add(5, 3) << std::endl;

    NumericOperations<double> doubleOps;
    std::cout << "5.5 - 3.2 = " << doubleOps.subtract(5.5, 3.2) << std::endl;

    // This will cause a compile-time error:
    // NumericOperations<std::string> stringOps;

    return 0;
}
Back to assertions