I have a class template Foo<T> .
I would like to implement a non-member Bar function that takes two Foo and returns a Foo . I want Bar be non-member, because for subscribers it is more natural to write Bar(f1, f2) than f1.Bar(f2) . I also want Bar be inline , because the calculation is trivial and frequent.
template <typename T> inline Foo<T> Bar(const Foo<T> &lhs, const Foo<T> &rhs) { ... }
The stunt Bar needs access to Foo private data. I would prefer not to have access to private data - there is no reason to publish personal data for users. Therefore, I would like to make Bar friend of Foo .
template <typename T> class Foo { ... private: T w, x, y, z; friend Foo<T> Bar(const Foo<T> &lhs, const Foo<T> &rhs); };
Here, where I run into trouble. The compiler complains:
The built-in specifier cannot be used when a friend declaration refers to the specialization of a function template.
Is this rule an introduced standard or is it specific to MSVC ++?
Here is what I tried:
Make Bar a public member function const, and then declare a non-member version that just returns lhs.Bar(rhs) . This seems like the least hacky solution.
Remove the inline hint, knowing that the compiler will solve the embedding issue regardless of the hint. Does this mean that it contradicts the rule of one definition? It still needs to be defined in the header file because it is a function template.
Declare a member function with a template type dummy:
template <typename T> class Foo { ... private: T w, x, y, z;
I'm not quite sure why this works, but it suits the compiler.
Is there a better solution?
c ++ friend function-templates
Adrian mccarthy
source share