There is an error when including "x.h" below from multiple C++ source files.
x.cpp:(.text+0x0): multiple definition of `void f(A&, B const&)'
/tmp/ccdXc4Sz.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
What happens here? How can it be rewritten to work?
x.h
#pragma once
#include <iostream>
struct B
{
int x, y;
};
struct A
{
template <class T>
friend void f(A& a, const T& t);
private:
int x {0};
};
template <class T>
void f(A& a, const T& t) { std::cout << a.x++ << ": " << t << std::endl; }
template <>
void f(A& a, const B& b) { std::cout << a.x++ << ": " << b.x << "," << b.y << std::endl; }
main.cpp
#include "x.h"
int main()
{
A a;
B b;
f(a, b);
return 0;
}
x.cpp
#include "x.h"