如何确定“自动”变量的实际类型

新手上路,请多包涵

在这个回复中:

https://stackoverflow.com/a/14382318/1676605

给出了这个程序:

 std::vector<int> vi{ 0, 2, 4 };
std::vector<std::string> vs{ "1", "3", "5", "7" };
for (auto i : redi::zip(vi, vs))
    std::cout << i.get<0>() << ' ' << i.get<1>() << ' ';

我不知道 auto i 的类型是什么,这使得重用专业知识和从示例中学习变得更加困难。这是将 auto i 更改为 char i 返回的内容

In function ‘int main()’:|
/data/cbworkspace/TestZip/TestZip.cpp|14|error: cannot convert ‘boost::iterator_facade<boost::zip_iterator<boost::tuples::tuple<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, __gnu_cxx::__normal_iterator<int*, std::vector<int> > > >, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, boost::random_access_traversal_tag, boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >, long int>::reference {aka boost::tuples::cons<int&, boost::tuples::cons<int&, boost::tuples::null_type> >}’ to ‘char’ in initialization|
/data/cbworkspace/TestZip/TestZip.cpp|14|warning: unused variable ‘i’ [-Wunused-variable]|
||=== Build finished: 1 errors, 1 warnings (0 minutes, 0 seconds) ===|

尝试从中找出类型。

有没有办法找出 auto 的变量在 C++11 中的类型是 什么?更清楚地说,我有一个 struct 像这样:

 struct EventData
{
    // return value from redi::zip<std::vector<PriceQuote>, std::vector<PriceQuote>> what goes here????? So REDI::Zip is zipping PriceQuote, PriceQuote of bids and asks.
};

struct PriceQuote
{
   double price;
   double size;
};

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

阅读 368
2 个回答

为什么要将该类型放入结构中?它并不是真的被设计成那样使用的(我应该知道,我写的!)但如果有必要,你可以使用 decltypestd::declval 来确定类型(它仍然会给出如果我更改 redi::zip 的实现,则正确答案)

 struct EventData
{
  // type returned by redi::zip
  typedef decltype(redi::zip(std::declval<V1>(), std::declval<V2>())) zipper_type;

  // type referred to by zipper_type::iterator
  typedef std::iterator_traits<zipper_type::iterator>::value_type zipped_type;

  zipper_type m_zipper;
};

注意为什么要为 --- 创建一个 typedef struct ?这是 C++ 而不是 C,停止它。

我不知道 auto i 的类型是什么,这使得重用专业知识和从示例中学习变得更加困难。

习惯它。你知道 std::bind 返回的类型吗?你知道 std::mem_fn 返回的类型吗?你知道 lambda 表达式创建的类型吗?不,你不需要知道,你只需要知道它有什么属性和 _你能用它做什么_,而不是它叫什么或者它包含什么类型。

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

尝试将 auto 更改为 char 并阅读错误消息。

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

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