This code:
template <typename T>
struct A
{
T t;
void DoSomething()
{
t.SomeFunction();
}
};
struct B
{
};
A<B> a;
is easily compiled without any complaints, as long as I never call a.DoSomething()
.
However, if I define DoSomething
as a virtual function, I will get a compile error saying that B
doesn't declare SomeFunction
. I can somewhat see why it happens (DoSomething should now have an entry in the vtable), but I can't help feeling that it's not really obligated. Plus it sucks.
Is there any way to overcome this?
EDIT 2: Okay. I hope this time it makes sence: Let's say I am doing intrusive ref count, so all entities must inherit from base class Object. How can I suuport primitive types too? I can define:
template <typename T>
class Primitive : public Object
{
T value;
public:
Primitive(const T &value=T());
operator T() const;
Primitive<T> &operator =(const T &value);
Primitive<T> &operator +=(const T &value);
Primitive<T> &operator %=(const T &value);
// And so on...
};
so I can use Primitive<int>
, Primitive<char>
...
But how about Primitive<float>
? It seems like a problem, because floats don't have a %=
operator. But actually, it isn't, since I'll never call operator %=
on Primitive<float>
.
That's one of the deliberate features of templates.
If, for some reason, I would define operator %=
as virtual. Or, if i'll pre-export Primitive<float>
from a dll to avoid link errors, the compiler will complain even if I never call operator %=
on a Primitive<float>
. If it would just have fill in a dummy value for operator %=
in Primitive<float>
's vtable (that raises an exception?), everything would have been fine.