使用“自动”类型推导 \- 如何找出编译器推导的类型?

新手上路,请多包涵

如何找出编译器在使用 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)

原文由 kmiklas 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 448
2 个回答

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

  template<typename T> struct TD;

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

  TD<decltype(var)> td;

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

原文由 marcinj 发布,翻译遵循 CC BY-SA 3.0 许可协议

typeid 大多数时候可以用来获取变量的类型。它依赖于编译器,我已经看到它给出了奇怪的结果。 g++ 默认开启 RTTI,在 Windows 端不确定。

 #include <iostream>
#include <typeinfo>
#include <stdint.h>
#include <chrono>
#include <ctime>

typedef std::ratio<1, 1> sec;
int main()
{
    auto tickTime = .001;
    std::chrono::duration<double, sec > timePerTick2{0.001};
    auto nextTickTime = std::chrono::high_resolution_clock::now() + timePerTick2;
    std::cout << typeid(tickTime).name() << std::endl;
    std::cout << typeid(nextTickTime).name() << std::endl;

    return 0;
}

./a.out | c++filt

double
std::__1::chrono::time_point<std::__1::chrono::steady_clock, std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000000000l> > >

原文由 Matthew Fisher 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题