Home > Software engineering >  Friend Function name undefined
Friend Function name undefined

Time:10-14

I tried to pass a friend function name comp to set_intersection, compiled in Visual Studio 2019 with a compilation error: E0020 identifier "comp" is undefined

#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);
}

However, if I changed comp to operator<, it works fine with set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(rs));. Why comp doesn't work?

CodePudding user response:

comp is not visible for lookup here. For 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

(Note that ADL only works for function-call expressions, i.e. comp(...);.)

You need to provide a declaration at the global namespace.

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);
}
  • Related