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 {
public:
    Foo(int v) : v(v) {}
 
private:
    template<typename T> friend class Bar; // magic incantation
 
    int v;
};
 
template<typename T>
class Bar {
public:
    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