[utility] Proposal of a utility component

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

Wang Weiwei wrote:
template <typename destination_type, typename source_type> destination_type force_cast(source_type s) { union { source_type s; [...]
Looks like an almost failsafe recipe for disaster ;-). It isn't safe to use 'union' in a generic context like this one. Union members should be of POD type (BTW. that's why there is Boost.Variant).
... a pointer to non-virtual function is actualy a normal function pointer:
Another dangerous assumption: With MSVC's __thiscall calling convention (the default setting of this compiler) the this-pointer is passed in a CPU register (namely ECX) and not on the stack... Sorry for all the bad news, Tobias P.S: An array_cast that allows to change array bounds and dimensions (with checking, in contexts where possible) would have my vote (that is, if it's not in Boost already, somewhere)...
participants (2)
-
Tobias Schwinger
-
Wang Weiwei