April 14, 2006
Too Many Templates
When you're lost in template land, instead of asking "how can I make this $*#*&& template work," ask yourself whether the problem you're seeing might have nothing to do with templates.
All too often you see questions on newsgroups about template code that doesn't compile. Many times the problem has nothing to do with templates; they're just a distraction. So try the same thing without templates and see if you can get it to work. Then take the lesson you learned over into your template code.
For example someone recently tried to derive from two different instantiations of the same template:
template struct S
{
void f(S);
};
struct Derived : S, S
{
void g()
{
f(1);
}
};
The code went on to create an object of type Derived and call its member function g. Didn't work: the compiler said the call to f(1) was ambiguous.
Try it with two ordinary classes instead of a template:
struct S_int
{
void f(int);
};
struct S_double
{
void f(double);
};
struct Derived : S_int, S_double
{
void g()
{
f(1);
}
};
Same error, same problem: the two versions of f don't overload, because they're not defined in the same scope.
Templates have a well-deserved reputation for creating nasty error messages. But sometimes it's not the template's fault.
Posted by Pete Becker at 01:04 PM Permalink
|