如何创建value_type型特征?
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
。
相关文章:
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 特征命名访问向量段
- 将特征矩阵的向量设置为0
- 特征:模板函数中矩阵的平面图
- basic_string的前导/尾部不区分空格的特征
- 在 QVector<std::unique_ptr 上使用 std::find<Type>>
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- 特征 3 类的模板专用化
- 特征 c++:复矩阵的面积双曲正切(atanh)
- 控制到达非空函数clang(-Wreturn-type)的末尾
- C++ 中的特征向量计算
- 根据C++标准的定义实现"is_similar"类型特征
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- 有没有办法找到特征矩阵系数的中值?
- `type'和`const type'的类型特征
- 对于类型修改特征,我是否应该为 typename::transform<...>::type 提供一个模板 typedef(又名使用)方便包装器?