C++中的泛型编程是一种编写可重用、可适应多种数据类型的编程方法。C++11引入了模板,使得泛型编程变得更加容易。以下是一些C++实现泛型编程的技巧:
template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
#include <type_traits>
template <typename T, typename std::enable_if<std::is_integral<T>::value, int>::type = 0>
void print(T value) {
std::cout << "Integer: " << value << std::endl;
}
template <typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
void print(T value) {
std::cout << "Floating point: " << value << std::endl;
}
#include <type_traits>
template <typename T, typename U>
void foo() {
if constexpr (std::is_same_v<T, U>) {
std::cout << "T and U are the same type" << std::endl;
} else {
std::cout << "T and U are different types" << std::endl;
}
}
#include <algorithm>
#include <vector>
int main() {
std::vector<int> v = {3, 1, 4, 1, 5, 9};
std::sort(v.begin(), v.end());
return 0;
}
template <typename T>
class MyClass {
public:
void print() {
std::cout << "Generic implementation" << std::endl;
}
};
template <>
class MyClass<int> {
public:
void print() {
std::cout << "Integer implementation" << std::endl;
}
};
template <>
class MyClass<std::string> {
public:
void print() {
std::cout << "String implementation" << std::endl;
}
};
通过使用这些技巧,你可以在C++中实现更通用、更灵活的泛型编程。