c++ - 使用 'auto' 类型推导 - 如何找出编译器推导的类型?

标签 c++ c++11 auto chrono

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

示例 1:更简单

auto tickTime = 0.001;

这是推导出为 float 还是 double?

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

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 时。我收到以下错误:

./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++ 中的想法,它使用未实现的模板;类型是编译器错误输出:

 template<typename T> struct TD;

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

 TD<decltype(var)> td;

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

关于c++ - 使用 'auto' 类型推导 - 如何找出编译器推导的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820579/

相关文章:

c++ - 无法推断出 const auto&

C++ 在结构/类包装器中重载自动运算符

templates - 虚函数可以用auto参数代替吗?

c++ - 结构的离散分布

C++ 继承结构

c++ - vector 问题,C++ 不确定我做错了什么

c++ - windows下建vst时如何使用外部dll

C++ 函数(附​​加费和常量)

c++ - simple_type_specifier 不支持 nullptr_type

c++ - Windows 应用商店应用程序 - 添加项目引用警告