我正在尝试按照这些方式做一些事情:

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

但是令人惊讶的是,惊喜它行不通。我怎样才能解决这个问题?
谢谢。

有帮助吗?

解决方案

您可以使用类型:

int the_max = std::numeric_limits<int>::max()

您可以使用辅助功能模板:

template <typename T>
T type_max(T)
{
    return std::numeric_limits<T>::max();
}

// use:
int x = 0;
int the_max = type_max(x);

在C ++ 0x中,您可以使用 decltype:

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

其他提示

typeid 不返回类型,而是运行时 type_info 目的。该模板参数期望编译时类型,因此它无法正常工作。

在像GCC这样的一些编译器中,您可以使用

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

否则,您可以尝试 boost.typeof.

在C ++ 0x中,您可以使用

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

(顺便提一句, @詹姆斯 type_max 如果您不需要明确的类型,那就好多了。)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top