[英]How can I create a value_type type trait?
我正在編寫一個程序,它將大量處理不同類型的字符串(即std::string
、 std::string_view
、 const char*
、 char[]
和具有不同CharT
朋友)。 因此,我對編寫一個可以抽象獲取泛型類數組結構的值類型的特征很感興趣。 對於前面列出的類型,正確的返回類型是char
。
但是,我似乎無法正確執行以允許泛型類型。 考慮以下嘗試:
template<class T>
struct value_type{
using type = std::conditional_t<
std::is_class_v<T>,
typename T::value_type,
std::conditional_t<
std::is_pointer_v<T>,
std::remove_pointer_t<T>,
// etc.
>;
};
這當然不能編譯,因為並非所有類型都有嵌套的value_type
typedef。
有沒有辦法有效地實現這個特性?
您可能會使用專業化(和 SFINAE):
template<class T, Enabler = void>
struct value_type;
template<class T>
struct value_type<T, std::void_t<typename T::value_type>>
{
using type = typename T::value_type;
};
template<class T>
struct value_type<const T*>
{
using type = T;
};
template<class T, std::size_t N>
struct value_type<const T[N]>
{
using type = T;
};
// ...
您可以遵循幫助程序類模板。 幸運的是,在隱式實例化期間不會實例化類型別名:
template <class T>
struct get_value_type {
using type = typename T::value_type;
};
template <class T>
struct value_type {
using type = typename std::conditional_t<
std::is_class_v<T>,
get_value_type<T>,
std::conditional<std::is_pointer_v<T>, std::remove_pointer_t<T>, void>
>::type;
};
這還需要您將第二個std::conditional_t
更改為std::conditional
以便我們可以從返回的任何類型中獲取::type
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.