gpt4 book ai didi

c++ - 为什么 clang 要求在模板中调用函数之前先声明该函数?

转载 作者:行者123 更新时间:2023-12-02 02:02:56 24 4
gpt4 key购买 nike

我有以下代码示例(可在线访问 coliru ):

#include <iostream>
#include <utility>

struct Bar {
int a;
};

template <class T>
void print_arg(const T& arg) {
std::cout << arg << std::endl;
}

std::ostream& operator<<(std::ostream& os, const Bar& b) {
os << b.a;
return os;
}

template <class T1, class T2>
std::ostream& operator<<(std::ostream& os, const std::pair<T1, T2>& pair) {
os << "Pair(" << pair.first << ',' << pair.second << ")";
return os;
}

int main()
{
auto bar = Bar{1};
print_arg(bar);
print_arg(std::make_pair(bar, bar));
print_arg(std::make_pair(bar, 1));
print_arg(std::make_pair(0, 1));
}

主函数中的最后一行给我带来了麻烦。使用 g++ 编译效果很好(具有与下面完全相同的选项),我启动可执行文件,它按预期打印所有内容。但是,Clang++ 给了我以下错误:

$ clang++ -std=c++17 -O2 -Wall -Werror -Wpedantic main.cpp && ./a.out
main.cpp:10:15: error: call to function 'operator<<' that is neither visible in the template definition nor found by argument-dependent lookup
std::cout << arg << std::endl;
^
main.cpp:29:5: note: in instantiation of function template specialization 'print_arg<std::pair<int, int> >' requested here
print_arg(std::make_pair(0, 1));
^
main.cpp:19:15: note: 'operator<<' should be declared prior to the call site
std::ostream& operator<<(std::ostream& os, const std::pair<T, T>& pair) {
^
1 error generated.

此外,删除最后一行(将其注释掉)会导致 Clang++ 正确编译所有内容。据我所知,这意味着 std::pair<int, int>与其他参数类型有质的不同。

我的问题是,为什么 g++ 无论如何都要编译它?更重要的是,为什么 clang 认为声明 operator<<(ostream, pair<Bar, Bar>) 是可以的稍后,但是 operator<<(ostream, pair<int, int>) 就不行了。是因为后者只包括标准型和基本型吗?

对我来说,(有点)合乎逻辑的事情似乎是,仅在标准/基本类型上定义函数是 UB,但 g++ 默默地忽略它,并且 clang++ 给出了一条看起来很奇怪的错误消息。然而,这对我来说没有多大意义,我找不到相关的标准条款。

注意:我知道将声明向上移动是 clang 所要求的,但我不明白为什么。我要提供print_arg函数在单独的 header 中,并允许包含该 header 的人专门化 operator<<使用print_arg时.

最佳答案

查看Language Compatibility : Unqualified lookup in templates部分。它准确地解释了这个案例。

总结是 GCC 编译有 bug 的代码,而 clang 遵循标准。

关于c++ - 为什么 clang 要求在模板中调用函数之前先声明该函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60242409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com