用类模板实现整数加法,小数加法,复数加法
时间: 2024-03-27 16:40:57 浏览: 72
好的,我可以为您提供这个类模板的实现:
```c++
#include <iostream>
#include <type_traits>
template<typename T>
class Adder {
public:
static_assert(std::is_arithmetic<T>::value, "Adder only supports arithmetic types");
T operator()(T a, T b) const {
return a + b;
}
};
template<typename T>
class Adder<std::complex<T>> {
public:
std::complex<T> operator()(const std::complex<T>& a, const std::complex<T>& b) const {
return a + b;
}
};
int main() {
Adder<int> int_adder;
std::cout << int_adder(1, 2) << std::endl;
Adder<double> double_adder;
std::cout << double_adder(1.5, 2.5) << std::endl;
Adder<std::complex<double>> complex_adder;
std::cout << complex_adder(std::complex<double>{1.0, 2.0}, std::complex<double>{3.0, 4.0}) << std::endl;
return 0;
}
```
这个类模板可以支持整数加法、小数加法和复数加法。当使用 `Adder<T>` 时,如果 `T` 是算术类型(即 `int`、`float`、`double` 等),则使用 `operator()` 对两个数进行加法运算。如果 `T` 是复数类型,则使用复数的加法运算。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)