小弧光的博客

公众号:小弧光黑板报

导航

写一个c++模板函数,支持int类型相加,string类型相加以及 string和int相加

要实现一个支持int类型相加、string类型相加以及string和int相加的C++模板函数,你可以使用函数重载和模板特化来实现这个目标。以下是一个示例实现:

#include <iostream>
#include <string>

// 模板函数:支持int类型相加
template<typename T>
T add(T a, T b) {
    return a + b;
}

// 函数重载:支持string类型相加
std::string add(const std::string& a, const std::string& b) {
    return a + b;
}

// 模板特化:支持string和int相加
template<>
std::string add(std::string a, int b) {
    return a + std::to_string(b);
}

template<>
std::string add(int a, std::string b) {
    return std::to_string(a) + b;
}

int main() {
    int intResult = add(3, 4);
    std::cout << "intResult: " << intResult << std::endl;

    std::string stringResult = add("Hello, ", "world!");
    std::cout << "stringResult: " << stringResult << std::endl;

    std::string mixedResult = add("The answer is: ", 42);
    std::cout << "mixedResult: " << mixedResult << std::endl;

    std::string mixedResult2 = add(100, " apples");
    std::cout << "mixedResult2: " << mixedResult2 << std::endl;

    return 0;
}

在这个例子中,我们使用了模板函数add()来支持int类型相加。然后,我们通过函数重载来支持string类型相加,即重载了add()函数以接收两个const引用的std::string参数。最后,我们使用模板特化,针对string和int的组合进行处理,即重载了add()函数以接收一个std::string和一个int参数或者一个int和一个std::string参数。

main()函数中,我们展示了对这些不同类型的参数进行相加的示例。这样你就可以灵活地使用add()函数进行不同类型的相加操作。

posted on 2023-07-31 11:20  小弧光  阅读(76)  评论(0编辑  收藏  举报