如何将引用类型转换为值类型
How can I convert a reference type to a value type?
我试图使用新的decltype
关键字将一些代码移动到模板中,但当与取消引用的指针一起使用时,它会产生引用类型。SSCCE:
#include <iostream>
int main() {
int a = 42;
int *p = &a;
std::cout << std::numeric_limits<decltype(a)>::max() << 'n';
std::cout << std::numeric_limits<decltype(*p)>::max() << 'n';
}
第一个numeric_limits
有效,但第二个抛出value-initialization of reference type 'int&'
编译错误。如何从指向该类型的指针中获取值类型?
您可以使用std::remove_reference
使其成为非引用类型:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
现场演示
或:
std::numeric_limits<
std::remove_reference_t<decltype(*p)>
>::max();
为了稍微不那么冗长的东西。
如果您要从一个指针转到被指向的类型,为什么还要取消对它的引用呢?只是,好吧,删除指针:
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << 'n';
// or std::remove_pointer<decltype(p)>::type pre-C++14
我想你想删除引用以及潜在的const
,所以你应该使用
std::numeric_limits<std::decay_t<decltype(*p)>>::max()
相关文章:
- 哪些类型可以转换为std::any
- 基于返回类型的转换和过载扣除
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- C++:将模板类型 char 转换为 std::string
- 由于类型从 C 转换为 C++,无法编译错误 C2440
- 在 Rcpp 中的字符串类型之间转换时出错
- C++隐式构造函数转换,后跟类型向上转换
- LLVM 无法将数组类型强制转换为常量数组
- 另一个:从"常量类型*"到"类型*"的转换无效
- 在不同类型之间转换常量指针
- C++可变参数模板类型筛选转换
- C++类型强制转换指向常量变量的指针
- 如何定义从标准类型到用户定义类型的转换?
- 编译错误 QT - 无法从类型强制转换
- 将模板类型名称转换为 uint64
- 为什么类型可转换性C++不传递
- 是否可以使用元编程将类型列表转换为对列表中每种类型具有特定隐式转换行为的新类型?
- 如何处理警告:从较小的整数类型int转换为int*
- 在函数指针类型之间转换
- Linux 编译错误 - 无法将类型"字符串"转换为类型"字符串&&"