[英]Getting type of an object
I'm trying to do something along these lines: 我试图沿着这些方向做点什么:
int var = 5;
std::numeric_limits<typeid(var)>::max();
but surprise, surprise it doesn't work. 但令人惊讶的是,它不起作用。 How can I fix this?
我怎样才能解决这个问题?
Thanks. 谢谢。
You can use the type: 您可以使用以下类型:
int the_max = std::numeric_limits<int>::max()
You can use a helper function template: 您可以使用辅助函数模板:
template <typename T>
T type_max(T)
{
return std::numeric_limits<T>::max();
}
// use:
int x = 0;
int the_max = type_max(x);
In C++0x you can use decltype
: 在C ++ 0x中,您可以使用
decltype
:
int x = 0;
int the_max = std::numeric_limits<decltype(x)>::max();
typeid
does not return a type, but a runtime type_info
object. typeid
不返回类型,而是返回运行时type_info
对象。 That template parameter expects a compile-time type, so it won't work. 该模板参数需要编译时类型,因此不起作用。
In some compilers like gcc, you could use 在像gcc这样的编译器中,你可以使用
std::numeric_limits<typeof(var)>::max();
Otherwise, you could try Boost.Typeof . 否则,您可以尝试Boost.Typeof 。
In C++0x, you could use 在C ++ 0x中,您可以使用
std::numeric_limits<decltype(var)>::max();
(BTW, @James's type_max
is much better if you don't need the type explicitly.) (顺便说一句,如果你不需要明确的类型, @ James的
type_max
要好得多。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.