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

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

问题描述

如何找出使用auto关键字时编译器推断出的类型?

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

示例1:更简单

auto tickTime = 0.001;

被推导为floatdouble?

示例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天全站免登陆