我試圖為能夠索引到例如std::vector的型別撰寫型別特征,這應該包括列舉型別,因為我可以將它們投到它們的底層型別。
到目前為止,我已經寫了以下特質。
#include <iostream>
#include <type_traits>
#include <cinttypes>/span>
#include <vector>
#include <utility>
template<typename T>
struct is_unsigned_integral 。
std::integral_constant<。
bool。
std::is_integral<T>::value &&。
std::is_unsigned<T>:value
> {}。
template<typename T>
inline constexpr auto is_unsigned_integral_v =
is_unsigned_integral<T>::value。
template<typename, typename = void>
struct is_index : std::false_type {};
template<typename T>
struct is_index<
T,
std::enable_if_t<。
is_unsigned_integral_v<。
std::conditional_t<。
std::is_enum_v<T>。
std::underlying_type_t<T>。
T
>
>
>
>:std::true_type {}。
template<typename T>
inline constexpr auto is_index_v = is_index<T> ::value。
enum class idx : unsigned int {};
int main() {
static_assert(is_index_v<unsigned int>, "") 。
static_assert(is_index_v<idx>, "") 。
return 0。
但我得到以下錯誤資訊
type_traits:2009:15: error:
只有列舉型別有底層型別
typedef __underlying_type(_Tp) type。
我希望出現以下情況
std::conditional_t<
std::is_enum_v<T>。
std::underlying_type_t<T>。
T
>。
評估8er到T或到底層型別是T是enum。
我將如何使其作業?
我將如何使其作業?
uj5u.com熱心網友回復:
替換失敗是因為沒有std::underlying_type_t<unsigned int>。
你可以單獨進行專業化處理:
#include <iostream>
#include <type_traits>
#include <cinttypes>/span>
#include <vector>
#include <utility>
template<typename T>
struct is_unsigned_integral 。
std::integral_constant<。
bool。
std::is_integral<T>::value &&。
std::is_unsigned<T>:value
> {}。
template<typename T>
inline constexpr auto is_unsigned_integral_v =
is_unsigned_integral<T>::value。
template<typename, typename = void>
struct is_index : std::false_type {};
template<typename T>
struct is_index<
T,
std::enable_if_t< is_unsigned_integral_v<T> >
> : std::true_type {};
template <typename T>
struct is_index<T,std::enable_if_t<std: :is_enum_v<T> >> : is_index<std::underlying_type_t<T> > {};
template<typenameT>
inline constexpr auto is_index_v = is_index<T> ::value。
enum class idx : unsigned int {};
int main() {
static_assert(is_index_v<unsigned int>, ""/span>)。
static_assert(is_index_v<idx>, "") 。
return 0。
PS:從cppreference/std::underlying_type/a>
如果 T 是一個完整的列舉(enum)型別,提供一個成員型別化的型別,命名 T 的底層型別。否則,該行為是未定義的。(直到C 20)
否則,如果T不是一個列舉型別,就沒有成員型別。否則(T是一個不完整的列舉型別),程式就不符合格式。 (自C 20以來)
我不得不承認,我不確定未定義的邊界(在C 20之前)如何在你的例子中與SFINAE發生作用。不過,請注意,在上面的例子中這不是一個問題,因為它只使用了 std::underlying_type_t<T>,而 T 實際上是一個列舉型別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333762.html
標籤:
