Virtual Function Pointer "Caching" via Templates
Is there any legal way to do what I'm trying to do below:
-------------------------------------------------------------------------------------
struct A;
struct B;
struct I
{
virtual int foo() = 0;
template<typename T>
T& specialize(I& i)
{
if ( i.ty() == 1 )
return reinterpret_cast<A&>(i);
else // must be 2
return reinterpret_cast<B&>(i);
}
};
struct A : public I
{
int ty() { return 1;}
template<typename T>
void foo(T& t)
{
std::cout << t << std::endl;
}
};
struct B : public I
{
int ty() { return 2;}
template<typename T>
void foo(T& t)
{
std::cout << t << std::endl;
}
};
template<typename T>
void blah(I& i)
{
T& t = specialize(i);
for ( unsigned int i = 0; i < 1000000; ++i )
{
t.foo();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
I* i = new A();
// do many other things here
// deep inside code....
blah(*i);
}
-------------------------------------------------------------------------------------
Basically I have a situation in which I'd like to avoid the overhead
of a virtual function call in a place in code that is called many,
many, many times a second. I have an interface pointer somewhere in
code. I want to do some special function on these objects which
should likely also have share a common interface, but since these
objects are so fine-grained object, I'd like to avoid the overhead of
a virtual table here as well. I'm trying to disambiguate an interface
pointer into a templated type for purposes of executing a loop. Is
this possible somehow -- to introduce static polymorphism ....
Finally, is this even a problem I should even be concerned about?
Will a modern compiler make this optimization for me anyway?
Thanks in advance,
Mark
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]