零、实现自己的swap函数
template <class T> void swap ( T& a, T& b );
一、类型萃取
#include <string>
#include <iostream>
#include <type_traits>
using namespace std;
template<typename T>
void my_swap(T& a, T& b)
{
static_assert(not std::is_same<T, char*>::value, "type 'T' not support char*");
T temp = a;
a = b;
b = temp;
}
int main()
{
char* a = "Xun";
char* b = "Ye";
my_swap(a, b); // compile error
return 0;
}
编译结果:
二、利用模板特化禁止某种模板实例化
#include <string>
#include <iostream>
#include <type_traits>
using namespace std;
template<typename>
struct ParamChecker
{};
template<typename T>
void my_swap(T& a, T& b)
{
ParamChecker<T> check;
T temp = a;
a = b;
b = temp;
}
template<>
struct ParamChecker<char*>
{
private:
ParamChecker();
};
int main()
{
char* a = "Xun";
char* b = "Ye";
my_swap(a, b); // compile error
return 0;
}
编译结果:
这种方式有用,可能没有类型萃取直观。