C++ 如何将引用类型转换为值类型?
我试图使用newC++ 如何将引用类型转换为值类型?,c++,c++11,reference,decltype,C++,C++11,Reference,Decltype,我试图使用newdecltype关键字将一些代码移动到模板中,但是当与解引用指针一起使用时,它会生成引用类型。SSCCE: #include <iostream> int main() { int a = 42; int *p = &a; std::cout << std::numeric_limits<decltype(a)>::max() << '\n'; std::cout << std:
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';
}
#包括
int main(){
INTA=42;
int*p=&a;
std::cout您可以使用将其设置为非引用类型:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
std::数值限制<
std::remove_reference::type
>::max();
或:
std::数值限制<
标准::删除参考
>::max();
对于稍微不太详细的内容。您希望删除引用,以及我猜可能的const
ness,因此您可以使用
std::numeric_limits<std::decay_t<decltype(*p)>>::max()
std::numeric\u limits::max()
如果要从指针指向指向的类型,为什么还要费事取消对它的引用?只需删除指针:
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14
std::cout他为什么要准确地删除const
ness?std::numeric\u限制
对于const T
类型来说非常好。对于::type
如果OP没有C++14
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14