add Chapter08
This commit is contained in:
44
Chapter08/tmpt_concepts.cpp
Normal file
44
Chapter08/tmpt_concepts.cpp
Normal file
@@ -0,0 +1,44 @@
|
||||
#include <cstdio>
|
||||
#include <type_traits>
|
||||
|
||||
struct point {
|
||||
int x;
|
||||
int y;
|
||||
|
||||
point operator+(const point& other) const {
|
||||
return point{x + other.x, y + other.y};
|
||||
}
|
||||
|
||||
void print() {
|
||||
printf("x = %d, y = %d\r\n", x, y);
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
concept Arithmetic = std::is_arithmetic_v<T>;
|
||||
|
||||
|
||||
template<Arithmetic T>
|
||||
T add(T a, T b) {
|
||||
|
||||
T result = a + b;
|
||||
if constexpr (std::is_integral_v<T>) {
|
||||
printf("%d + %d = %d\r\n", a, b, result);
|
||||
} else if constexpr (std::is_floating_point_v<T>) {
|
||||
printf("%.2f + %.2f = %.2f\r\n", a, b, result);
|
||||
}
|
||||
|
||||
return a + b;
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
auto a = add(1, 2); // OK
|
||||
auto b = add(1.1, 2.1); // OK
|
||||
|
||||
point p_a{1, 2};
|
||||
point p_b{2, 1};
|
||||
auto c = add(p_a, p_b); // compile-error
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user