Friend 函数名称未定义
Friend Function name undefined
我试图将友元函数名称 comp
传递给 set_intersection
,编译于 Visual Studio 2019,出现编译错误:E0020 标识符“comp”未定义
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}
但是,如果我将 comp
更改为 operator<
,它可以与 set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs));
一起正常工作。为什么 comp
不起作用?
comp
在此处查找不可见。对于 friend declaration、
A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided
(请注意,ADL 仅适用于函数调用表达式,即 comp(...);
。)
您需要在全局命名空间中提供声明。
bool comp(const Test& A, const Test& B);
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}
我试图将友元函数名称 comp
传递给 set_intersection
,编译于 Visual Studio 2019,出现编译错误:E0020 标识符“comp”未定义
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}
但是,如果我将 comp
更改为 operator<
,它可以与 set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs));
一起正常工作。为什么 comp
不起作用?
comp
在此处查找不可见。对于 friend declaration、
A name first declared in a friend declaration within a class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided
(请注意,ADL 仅适用于函数调用表达式,即 comp(...);
。)
您需要在全局命名空间中提供声明。
bool comp(const Test& A, const Test& B);
class Test {
friend bool comp(const Test& A, const Test& B) { return A.a < B.a; }
public:
int a{ 10 };
};
int main() {
vector<Test> v1{ Test{} };
vector<Test> v2{ Test{} };
vector<Test> rs;
set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs), comp);
}