开发者

Getting type of an object

开发者 https://www.devze.com 2023-01-13 08:02 出处:网络
I\'m trying to do something along these lines: int var = 5; std::numeric_limits<typeid(var)>::max();

I'm trying to do something along these lines:

int var = 5;
std::numeric_limits<typeid(var)>::max();

but surprise, su开发者_C百科rprise 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:

int x = 0;
int the_max = std::numeric_limits<decltype(x)>::max();


typeid does not return a type, but a runtime type_info object. That template parameter expects a compile-time type, so it won't work.

In some compilers like gcc, you could use

std::numeric_limits<typeof(var)>::max();

Otherwise, you could try Boost.Typeof.

In C++0x, you could use

std::numeric_limits<decltype(var)>::max();

(BTW, @James's type_max is much better if you don't need the type explicitly.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号