mercredi 6 décembre 2017

Casting const references to and from void pointers

Problem: I have a class of parameters which I'm passing around as const Some_Class& param because these parameters aren't changing. I need to pass these parameters to external library (GSL) which is accepting void* param. I can't cast from const& to void*, except with using const_cast. I heared that const_cast is not generally right solution, is this the correct use case for it?

My solution: As a solution I'm now using wrapper structure

struct wrapper{const Some_class& param;};

void gsl_func(void* param){
    const Some_class& my_param = static_cast<wrapper*>(param)->param;
}

void my_func(const Some_class& my_param){
    wrapper my_wrapper = {my_param};
    gsl_func(&my_wrapper);
}

Which doesn't seems like the most elegant solution as I have to do this before every call to GSL. Is there some standardize way how to do this better?

Aucun commentaire:

Enregistrer un commentaire