Search code examples
c++templateslinkerfriend

Linker error when operator== is a friend


The following code is a minimum code to reproduce my problem. When I try to compile it, the linker can not find operator== for Config:

Undefined symbols for architecture x86_64:
"operator==(Config<2> const&, Config<2> const&)", referenced from:
          _main in test2.o

The operator== is a friend of Config. BUT when I do no longer declare operator== as a friend, the code compilers with no error.

template <int DIM>
class Config{
    // comment the following line out and it works
    friend bool operator==(const Config<DIM>& a, const Config<DIM>& b);

    public:
        int val;
};

template <int DIM>
bool operator==(const Config<DIM>& a, const Config<DIM>& b){
    return a.val == b.val;
}

int main() {
    Config<2> a;
    Config<2> b;
    a == b;
    return 0;
}

What is the problem here?


Solution

  • You have missed to declare the template in the friend declaration:

    template <int DIM>
    class Config{
        template <int DIM_> // <<<<
        friend bool operator==(const Config<DIM_>& a, const Config<DIM_>& b);
    
        public:
            int val;
    };
    

    If you want to have a friend function declaration you must use it's exact signature declaration. If this involves template parameters these must be specified independently from the enclosing template class or struct.


    Here's a brilliant answer explaining the several aspects of friend declarations in depth.