|
Boost : |
From: Wang Weiwei (wwwang_at_[hidden])
Date: 2006-02-03 22:17:39
Hello boosters,
I have a tiny component I hope it can attact any interst. It is one step forward of the built-in interpert_cast operator, a force_cast free function:
template <typename destination_type, typename source_type>
destination_type force_cast(source_type s)
{
union
{
source_type s;
destination_type d;
} u;
u.s = s;
return u.d;
}
Demonstration of use: The following code is to demonstrate a pointer to non-virtual function is actualy a normal function pointer:
class Shape
{
public:
virtual void Move(void) const=0;
virtual void Draw(void) const=0;
void Nonvirtual(void) const
{ std::cout << "Calling Shape::Nonvirtual(void)" << std::endl; }
};
class Triangle : public Shape
{
public:
virtual void Move(void) const {}
virtual void Draw(void) const {}
virtual void DrawTriangle(void) const {}
};
typedef void (Shape::*pmfb_t)(void) const;
pmfb_t pmfb_n = &Shape::Nonvirtual;
Triangle tri;
(tri.*pmfb_n)(); // 1
(force_cast<void (*)(Shape *)>(pmfb_n))(static_cast<Shape *>(&tri)); // 2
// or in a clearer manner
typedef void (*pf_t)(Shape *);
(force_cast<pf_t>(pmfb_n))(static_cast<Shape *>(&tri)); // 3
The output is:
Calling Shape::Nonvirtual(void) // from 1
Calling Shape::Nonvirtual(void) // from 2
Calling Shape::Nonvirtual(void) // from 3
Wang Weiwei
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk