can someone please shed some light on a curious phenomenon with C++ templates. Consider this simple code:
class B {};
template <typename T>
class A
{
T _v;
public:
A() {}
void add(T a) { _v += a; }
};
int main()
{
A<B> b;
return 0;
}
Clearly this isn't legal because the += operator is not defined for class B, and therefore the code inside the add
method is invalid. Yet this code compiles fine!
It is not until you call the add
method that you get a compile error:
int main()
{
A<B> b;
b.add(B()); // complains about a missing += operator
return 0;
}
For a non-template class the compile error occurs regardless of whether the class is used at all.
class C
{
B _v;
public:
C() {}
void add(B a) { _v += a; } // compile error here right away
};
Why is that? Thanks.