#include <iostream>
using namespace std;
template <class T> struct IsCharPointer {};
template <> struct IsCharPointer<char*> {
using type = int;
};
template <> struct IsCharPointer<const char*>{
using const_type = int;
using type = int;
};
int main() {
cout << boolalpha;
cout << IsCharPointer<int>::type << endl; // 不是字符型指针,没有定义 type 别名
cout << IsCharPointer<char*>::type << endl; // 是 char* 类型的指针,定义了 type 别名
cout << IsCharPointer<const char*>::type << endl; // 是 const char* 类型的指针,定义了 type 别名
cout << IsCharPointer<const char*>::const_type << endl; // 是 const char* 类型的指针,定义了 const_type 别名
return 0;
}
这段代码定义了一个模板结构体 IsCharPointer,用于判断模板类型参数是否为 char* 或 const char* 类型的指针。
具体来说,该结构体定义了一个模板类型参数 T,并为 char* 和 const char* 分别提供了偏特化版本。对于 char*,该结构体定义了一个内部类型别名 type,用于表示该类型是 char*。对于 const char*,该结构体定义了两个内部类型别名 const_type 和 type,分别用于表示该类型是 const char* 和 char*。
这个结构体的作用可以用于模板元编程中,根据模板类型参数是否为 char* 或 const char* 来进行不同的编译期判断和处理。例如,可以使用这个结构体来定义一个模板函数,只接受 char* 或 const char* 类型的指针参数,而对于其他类型的参数则进行编译期报错。
使用 C++17 或 C++20 可以采用另一种更简洁的写法,使用 std::is_same_v 模板实现判断。下面是使用 std::is_same_v 的示例代码:
template <class T>
struct IsCharPointer {
static constexpr bool value = std::is_same_v<T, char*> || std::is_same_v<T, const char*>;
};
下面是一个使用 IsCharPointer 结构体的示例 main 函数:
#include <iostream>
template <class T>
struct IsCharPointer {
static constexpr bool value = std::is_same_v<T, char*> || std::is_same_v<T, const char*>;
};
int main() {
std::cout << std::boolalpha;
std::cout << IsCharPointer<int>::value << std::endl; // false
std::cout << IsCharPointer<char*>::value << std::endl; // true
std::cout << IsCharPointer<const char*>::value << std::endl; // true
std::cout << IsCharPointer<const char* const>::value << std::endl;// true
return 0;
}
在 main 函数中,我们使用了 std::boolalpha 来输出布尔类型值为 true 或 false,使得输出结果更易读。然后我们分别调用了 IsCharPointer 结构体来判断不同类型参数是否为 char* 或 const char* 类型的指针,输出了其返回值。可以看到,在输出结果中,char* 和 const char* 的返回值都是 true,而其他类型的返回值均为 false。