将 auto 关键字替换为推导类型(clang 或 VS2010)
有没有人编写过脚本、插件或可执行文件,用编译器推导的类型替换“auto”的每个实例?我需要移植一些在各处使用 auto 的 C++11 代码。
Clang 是我的第一个候选人。有没有人修改过它来做这样的事情?
另一种方法是解析来自编译器的错误,因为错误输出中可能包含预期类型。我可以 -Dauto=int
并可能返回 “无法将 std::vector
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,这在一般情况下是不可能的。考虑一下:
诚然,这是一个毫无意义的示例,但它表明,当依赖于模板参数时,无法知道用什么替换 auto 。顺便说一句,
std::map
和std::set
包含同名的 typedef (iterator
),它们表示各自迭代器的类型,因此typename T::iterator it
可以在这里工作,但是您可以为没有此类 typedef 的T
实例化foo
。标准库类中的大量 typedef 被精确地添加,以允许在发明/重新利用
auto
之前编写此类模板,并且您可以做同样的事情来处理不支持的编译器有自动
。但这不是您可以自动化的东西,至少不需要付出与向编译器添加对auto
的支持相当的努力......即使
auto
不依赖于模板类型,用对用户有意义且便携的东西来替代它是一个难题。采取:auto
的合理替代是std::map::iterator
,但如果您使用-Dauto=int
并查看编译器错误消息,您可以将其替换为std::_Rb_tree_iterator; >
。这是标准库的实现细节,难以阅读并且显然不可移植——您不希望在代码中出现这样的情况。在你的例子中,我的编译器(GCC 4.4.6)说:
Unfortunately, this is impossible in the general case. Consider:
Admittedly a pointless example, but it shows that there's no way to know what to replace auto with, when dependent on a template argument.
std::map
andstd::set
, incidentally, contain typedefs of the same name (iterator
) that represent the type of the respective iterator, sotypename T::iterator it
would work here, but you can instantiatefoo
for aT
that does not have such a typedef.The numerous typedefs in the standard library classes were added exactly to allow such templates to be written before
auto
was invented/re-purposed, and you can do the same thing to deal with a compiler that doesn't haveauto
. But it's not something you can automate, at least not without an effort comparable to adding support forauto
to a compiler...Even when
auto
is not dependent on a template type, it is a difficult problem to replace it with something that makes sense to the user and is portable. Take:The reasonable replacement for
auto
isstd::map<int, int>::iterator
, but if you use-Dauto=int
and look at the compiler error messages, you'd replace it with something likestd::_Rb_tree_iterator<std::pair<const int, int> >
. That's implementation detail of the standard library, hard to read and obviously not portable -- you don't want that in your code.In your very example, my compiler (GCC 4.4.6) says: