败犬日报 2024-10-19
1. 编译期判断一个类型为常指针
cpp
#include <type_traits>
template <typename T>
concept IsConstPointer =
std::is_pointer_v<T> && std::is_const_v<std::remove_pointer_t<T>>;
template <typename T>
concept IsConstPointerV2 = requires {
requires std::is_pointer_v<T>;
requires std::is_const_v<std::remove_pointer_t<T>>;
};
// 没有 concept 可以这么写
template <typename T>
constexpr bool IsConstPointerV3 =
std::is_pointer_v<T> && std::is_const_v<std::remove_pointer_t<T>>;
int main() {
static_assert(IsConstPointer<const int*>);
static_assert(!IsConstPointer<int>);
static_assert(!IsConstPointer<const int>);
static_assert(!IsConstPointer<int*>);
}