Mmmm. Tori Amos. Black Coffee. Linear algebra. Grapefruit. Noir.

I learned a little something about Visual C++ last night, so I thought I'd share. Maybe I'll even write it in my Advogato diary. Without further ado... Let's say you want to separate a function into policies (for information about policy-based design, read the first chapter of Modern C++ Design) via templates. You'd typically define the function as such:

struct policyA {
  static void DoSomething() { print("policyA::DoSomething"); }
};

struct policyB {
  static void DoSomething() { print("policyB::DoSomething"); }
};

template<typename policy>
void foo() {
  // do whatever
  policy::DoSomething();
}

// ...

foo<policyA>(); // call foo, using policy A
foo<policyB>(); // call foo, using policy B

However, due to yet another VC++ template bug, both of those function calls generate the exact same code! It only ever uses one, arbitrarily determined, policy!

However, I've discovered a very straightforward workaround. You can define your function like:

template<typename policy>
void foo(policy = policy()) {
  policy::DoSomething();
}

That strange policy = policy() syntax specifies an unnamed parameter with a default value of a default instance of the policy. This little push is all VC++ takes to generate proper code. Your client code doesn't have to change at all, and the extra parameter adds minimal overhead, as most policy classes consist purely of static (or class) definitions, and therefore are 0 bytes in size.

When Visual Studio .NET comes out, I'll test to see if VC++ 7 still suffers from this problem.