C++ Template Friends

February 19, 2009

In case you don’t know how to befriend all instances of a template class:

#include <iostream>
using namespace std;
class Foo {
    Foo(int v) : v(v) {}
    template<typename T> friend class Bar; // magic incantation
    int v;
template<typename T>
class Bar {
    static int get(Foo& f) {
        return f.v;
int main() {
    Foo f(42);
    cout << Bar<int>::get(f) << endl;
    return 0;

This also works to befriend template functions and operators. It is not supported by MSVC6, however.

Tags: C++ fixme