3

Possible Duplicate:
What’s the scope of inline friend functions?

Consider simple program :

template<typename T> struct foo{
friend void bar(){}
};

int main(){
foo<int>(); foo<float>();
}

Above code breaks the ODR rule, I wonder why? , also where is the scope of function bar ?

Community
  • 1
  • 1
M3taSpl0it
  • 2,967
  • 6
  • 28
  • 27

3 Answers3

1

friend functions are not member functions; you just declare friendship inside a class, but the function is always a free function. If you define it inside a class template class, you will end up defining it as many times as template instances you have.

I will try to explain that with code. For our purposes, your code is equivalent to this:

template<typename T> struct foo{
};

template<> struct foo<int>{
  friend void bar();
};

void bar() {};

template<> struct foo<double>{
  friend void bar();
};

void bar() {};

int main(){
  foo<int>(); foo<float>();
}
Gorpik
  • 10,940
  • 4
  • 36
  • 56
1

Because your code defines the free function void bar() twice, or lets rather say, your templates produces for each instantiation a new function named void bar(), which happens to have the exact same signature each time, therefore you have multiple functions with the same signature, which is a breach of ODR.

The technique at hand is called "Friend Name Injection", because you inject a name into the surrounding namespace.

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
0

You have defined the bar inside your struct. This leads to double definition of bar func, once per template instantiation. Friend should be only a declaration of some entity. The entity itself (func in your case) should be defined elsewhere. Replace your bar definition with friend void bar(); declaration and define your bar in another place.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85