折叠表达式和函数名称查找 [英] fold expression and function name lookup

查看:50
本文介绍了折叠表达式和函数名称查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++ 17中的折叠表达式.我有以下代码

I am learning fold expressions in C++17. I have the following code

#include <iostream>
#include <vector>

namespace io {
template<typename T>
std::istream &operator>>(std::istream &in, std::vector<T> &vec) {
  for (auto &x : vec)
    in >> x;
  return in;
}

template<class... Args> void scan(Args &... args) {
  (std::cin >> ... >> args);
}
}// namespace io

int main() {
    std::vector<int> s(1), t(1);
    io::scan(s, t);
    std::cout << s[0] << ' ' << t[0] << '\n';
}

使用 GCC 9.3.0 ,代码可以编译并正常运行,但是使用 Clang 10.0.0 ,相同的代码无法编译:

Using GCC 9.3.0, the code compiles and runs correctly, but using Clang 10.0.0, the same code does not compile:

<source>:13:16: error: call to function 'operator>>' that is neither visible in the template definition nor found by argument-dependent lookup
  (std::cin >> ... >> args);
               ^
<source>:19:9: note: in instantiation of function template specialization 'io::scan<std::vector<int, std::allocator<int> >, std::vector<int, std::allocator<int> > >' requested here
    io::scan(s, t);
        ^
<source>:6:15: note: 'operator>>' should be declared prior to the call site
std::istream &operator>>(std::istream &in, std::vector<T> &vec) {
              ^
1 error generated.

为什么clang拒绝了代码,但gcc接受了?

Why clang rejets the code but gcc accepts it?

推荐答案

这是Clang错误.Clang版本11和更早版本没有正确地在折叠表达式中为运算符实现两阶段名称查找,并且会错误地从恰好执行折叠表达式实例化的词法范围而不是从词法范围中执行第一阶段查找从模板定义的上下文中进行第一阶段查找.

This was a Clang bug. Clang versions 11 and earlier did not properly implement two-phase name lookup for the operator in a fold expression, and would incorrectly perform the first-phase lookup from the lexical scope in which the instantiation of the fold-expression happened to be performed rather than doing the first-phase lookup from the context of the template definition.

相对较近地解决了该问题(不幸的是没有及时的解决Clang 11版本),并且测试用例现已 Clang主干接受.

I fixed this relatively recently (unfortunately not in time for the upcoming Clang 11 release), and the test case is now accepted by Clang trunk.

这篇关于折叠表达式和函数名称查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆