Scu*_*der 3 c++ reference decltype c++11
我正在尝试使用new 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';
}
Run Code Online (Sandbox Code Playgroud)
第一个numeric_limits工作,但第二个抛出value-initialization of reference type 'int&'编译错误.如何从指向该类型的指针获取值类型?
Sho*_*hoe 11
您可以使用std::remove_reference它使其成为非引用类型:
std::numeric_limits<
std::remove_reference<decltype(*p)>::type
>::max();
Run Code Online (Sandbox Code Playgroud)
要么:
std::numeric_limits<
std::remove_reference_t<decltype(*p)>
>::max();
Run Code Online (Sandbox Code Playgroud)
对于稍微不那么冗长的东西.
如果你从一个指向指向类型的指针,为什么还要解除引用呢?只是,好吧,删除指针:
std::cout << std::numeric_limits<std::remove_pointer_t<decltype(p)>>::max() << '\n';
// or std::remove_pointer<decltype(p)>::type pre-C++14
Run Code Online (Sandbox Code Playgroud)
你想删除引用以及const我猜的可能性,所以你要使用
std::numeric_limits<std::decay_t<decltype(*p)>>::max()
Run Code Online (Sandbox Code Playgroud)