Friday, September 08, 2006

Template argument dependent name lookup

Puzzle: What will be the output of the following program?

struct B {
void foo () {
printf ("B::foo");
}
};

void foo () {
printf("::foo");
}

template <typename Base>
struct Derived : public Base {
void bar () { foo (); }
};

int main (void) {
Derived <B> d;
d.bar();

return 0;
}

Answer: C++ compiler does not perform template argument dependent lookup because the rule is to lookup as many names as possible at the time of parsing the template the first time. It does not wait till the instantiation of it. So ::foo!

Friday, September 01, 2006

Named Parameter Idiom

I came across another C++ idiom which is "useful if a function takes a large number of mostly default-able parameters". You can check it out here. It makes use of a fairly common technique called Method Chaining. I am thinking of putting together a list of C++ idioms, which are spread across web and also the idioms from popular books.