Re: Reinterpret cast and CRTP
pfultz2 wrote:
When i use the curiously recurring template pattern, do i need to use
the reinterpret_cast to get the derived class or do i use the
static_cast?
static_cast. reinterpret_cast will typically only change the type associated
with an address (its actual workings are implementation defined).
static_cast will simply assume that the address is the result of a
conversion from the target type and adjust both the type and, in the case
of e.g. multiple inheritance, the address.
And is there a performance penalty in doing this cast?
For example
template<class Derived>
class Base
{
public:
void foo()
{
reinterpret_cast<Derived*>(this)->bar();
//or can i use a static cast here?
}
};
You _must_ use static_cast here.
class MyClass : Base<MyClass>
{
public:
void bar();
};
Try this:
struct test: std::string, Base<test>
{
test()
{
std::cout << this << std::endl;
}
void bar()
{
std::cout << this << std::endl;
}
};
Try this and compare the addresses, using both types of cast.
Im under the assumption that a static cast wouldnt work since the
derived class is not known at compile time.
It is not known when Base is first parsed, but it must be known when it is
instantiated, otherwise the call to bar() would be impossible. There is a
distinction between those two phases for templates!
Uli
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]