使用“自动"类型推导 - 如何找出编译器推导的类型? [英] Using 'auto' type deduction - how to find out what type the compiler deduced?

查看:38
本文介绍了使用“自动"类型推导 - 如何找出编译器推导的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何知道编译器在使用 auto 关键字时推导出的类型?

How can I find out what type the compiler deduced when using the auto keyword?

示例 1:更简单

auto tickTime = 0.001;

这被推导出为 float 还是 double?

Was this deduced as a float or a double?

示例 2:更复杂(以及我目前的头痛):

Example 2: More complex (and my present headache):

typedef std::ratio<1, 1> sec;
std::chrono::duration<double, sec > timePerTick2{0.001};
 auto nextTickTime = std::chrono::high_resolution_clock::now() + timePerTick2;

nextTickTime 是什么类型?

我遇到的问题是当我尝试将 nextTickTime 发送到 std::cout 时.我收到以下错误:

The problem I'm having is when I try to send nextTickTime to std::cout. I get the following error:

./main.cpp: In function ‘int main(int, char**)’:
./main.cpp:143:16: error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
  std::cout << std::setprecision(12) << nextTickTime << std::endl; // time in seconds
            ^
In file included from /usr/include/c++/4.8.2/iostream:39:0,
             from ./main.cpp:10:
/usr/include/c++/4.8.2/ostream:602:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<double, std::ratio<1l, 1000000000l> > >]’
 operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

推荐答案

我喜欢使用来自 Effective Modern C++ 的想法,它使用非实现模板;输出类型并带有编译器错误:

I like to use idea from Effective Modern C++ which uses non-implemented template; the type is output with compiler error:

 template<typename T> struct TD;

现在对于自动变量var,在其定义后添加:

Now for auto variable var, after its definition add:

 TD<decltype(var)> td;

并注意编译器的错误消息,它将包含 var 的类型.

And watch error message for your compiler, it will contain type of var.

这篇关于使用“自动"类型推导 - 如何找出编译器推导的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆