我正在尝试实现 is_similar
基于标准给出的定义的类型特征(详细信息 here ):
Two types
T1
andT2
are similar if they have cv-decompositions with the samen
such that correspondingPi
components are either the same or one is "array ofNi
" and the other is "array of unknown bound of", and the types denoted byU
are the same.
但是,我不确定到底是什么意思,以及如何实现它:
template <class T, class U, class = void>
struct is_similar_base: std::false_type {};
template <class T, class U>
struct is_similar_base<T, U, /* ??? */ >: std::true_type {};
template <class T, class U>
struct is_similar: is_similar_base<T, U> {};
template <class T, class U>
inline constexpr bool is_similar_v = is_similar<T, U>::value;
欢迎任何帮助。
最佳答案
cv-decomposition 将类型“剥离”成 const
的交替层/volatile
限定符和指针/数组间接。如果指针/数组间接相同(允许“未知边界数组”匹配“n
”数组)并且下面的类型相同(忽略 cv 限定符),则类型相似。
所以,
// every type is similar to itself
template<typename T, typename U>
struct is_similar_impl : std::is_same<T, U> { };
// we don't care about cv-qualifiers
template<typename T, typename U>
struct is_similar : is_similar_impl<std::remove_cv_t<T>, std::remove_cv_t<U>> { };
// peeling off different kinds of pointers/arrays
template<typename T, typename U>
struct is_similar_impl<T*, U*> : is_similar<T, U> { };
template<typename C, typename T, typename U>
struct is_similar_impl<T C::*, U C::*> : is_similar<T, U> { };
template<std::size_t N, typename T, typename U>
struct is_similar_impl<T[N], U[N]> : is_similar<T, U> { };
template<std::size_t N, typename T, typename U>
struct is_similar_impl<T[N], U[]> : is_similar<T, U> { };
template<std::size_t N, typename T, typename U>
struct is_similar_impl<T[], U[N]> : is_similar<T, U> { };
template<typename T, typename U>
constexpr inline bool is_similar_v = is_similar<T, U>::value;
Godbolt and test cases
关于c++ - 基于 C++ 标准的定义实现 `is_similar` 类型特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722937/