用c++实现一个可以计算两个双精度浮点数加法、两个整数的加法、连接两个字符串的函数模板add
时间: 2025-02-23 08:32:29 浏览: 41
C++实现这些功能通常会涉及不同的头文件和函数定义。以下是一些基本示例:
1. **双精度浮点数(double)加法**[^1]:
```cpp
#include <iostream>
using namespace std;
template<typename T> T add(T a, T b) {
return a + b;
}
int main() {
double d1 = 3.14, d2 = 2.71;
cout << "Sum of two doubles: " << add(d1, d2) << endl;
return 0;
}
```
2. **整数(int)加法**:
```cpp
int i1 = 10, i2 = 20;
cout << "Sum of two integers: " << add(i1, i2) << endl; // 注意这里直接使用普通加法,因为int类型可以直接相加
```
3. **字符串连接**(这里假设我们有一个`std::string`模板方法来处理,但C++标准库没有提供直接的模板方法连接字符串,通常使用`+`操作符或`append()`函数):
```cpp
#include <string>
template<typename T> void connectStrings(T str1, T str2) {
if (is_same<T, std::string>::value) { // 检查类型是否为std::string
std::string result = str1 + str2;
cout << "Concatenated strings: " << result << endl;
} else {
cerr << "Unsupported type for string concatenation." << endl;
}
}
// 使用时
connectStrings("Hello, ", "World!"); // 输出:Hello, World!
```
阅读全文
相关推荐

















