[partly: Boost.Function] typesafe (templated) wrapper around class with void* API

[This question has a Boost.Function relation later on.
Sorry if too off topic.]
I have a class that works on some data structures.
This class' API uses void* to be general and avoid
code duplication that using a template here would incur.
Basically:
class A // simplification
{
// Assume A to be a "fat" class there are more methods
// working on void*
// and lots of code put away into a .cpp file. We don't
// want that duplicated by many template instantiations.
public:
// Most of the work is generic and independent from the
// data types worked on.
void do_something(void*);
protected:
// some work has to be done be the subclass
virtual bool help_me(const void*) =0;
};
I do not like using void* all that much. Thus I would like
to create a type-safe (generic) thin wrapper class. Using
inline functions,the idea is that the run time penalty (at
least for do_something) is low and casts from/and to void
are all 'hidden' here.
template<typename T>
class B : public A
{
public:
void do_something(T* t) { A::do_something(t); }
protected:
// Force user to provide a correctly typed callback.
virtual bool help_me(const T*) =0;
private:
// call the user's safe callback
bool help_me(const void* t)
{
return help_me(static_cast

AMDG Christoph Duelli wrote:
template<typename T> class B : public A { public: void do_something(T* t) { A::do_something(t); } protected: // Force user to provide a correctly typed callback. virtual bool help_me(const T*) =0; private: // call the user's safe callback bool help_me(const void* t) { return help_me(static_cast
(t)); } }; More specific questions: i) I assume the penalty for my callback "help_me" is one more indirection. Can't see that optimized away.
Use CRTP
template
ii) Assuming A's interface gets passed a real callback function (a Boost.Function) instead:
class A { public: typedef boost::function
helper_func; void do_something(void*, helper_func); }; is it somehow possible to get a typesafe templated B such that template<typename T> class B : public A { public: typedef boost::function
helper_func; void do_something(T* t, helper_func hf) { // this makes my compiler unhappy (when instanced). // I do understand that... can it be worked around somehow? A::do_something(t, hf); } };
A::do_something(t, boost::lambda::bind(hf,
boost::lambda::ll_static_cast

Use CRTP template
class B { private: bool help_me(const void* t) { return static_cast (this)->help_me(static_cast (t)); } }; Indeed. Thank you.
A::do_something(t, boost::lambda::bind(hf, boost::lambda::ll_static_cast
(boost::lambda::_1))); ok. Thanks again!
Christoph
participants (2)
-
Christoph Duelli
-
Steven Watanabe