使用变量的类型作为模板参数

Sil*_*cer 2 c++ types c++11 c++14 c++17

我做了以下事情:

long long int x = 0;
int digits_of_x = std::numeric_limits<long long int>::digits;
Run Code Online (Sandbox Code Playgroud)

它工作正常.但是,如果有人更改了类型,这很容易引入错误x.所以我更喜欢这样做:

long long int x = 0;
int digits_of_x = std::numeric_limits<typeof(x)>::digits;
Run Code Online (Sandbox Code Playgroud)

我找到了GCC扩展,typeof()但我想使用一些标准函数(最多C++ 17).有这样的功能吗?

acm*_*acm 6

你想要使用decltype,而不是typeof.从C++ 11开始提供:

long long int x = 0;
int digits_of_x = std::numeric_limits<decltype(x)>::digits;
Run Code Online (Sandbox Code Playgroud)