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++中實現更通用、更靈活的泛型編程。