So I am currently writing an abstraction layer for some embedded systems. I normally do this in C, but i want to see if I can't work in some C++ to learn a little.
I've run into an issue because I'm trying to abstract out a Usart class. The hw init needs to have hardware specific arguments, so I'm struggling to do this in cpp. In C, I could just pass a void pointer and cast the void argument to the type of my choice, but I can't do this in C++ for some reason. I also imagine there's a better way to do this in C++ that is safer so I'd like to go that route if possible. It'd be really cool to have this pass or fail at compile time and not at runtime. This is my idea so far:
#include <iostream>
#include <cstdint>
class Usart
{
public:
Usart(){}
~Usart(){}
virtual int configure(void* hw_args)
{
if(hw_args == NULL)
{
return -1;
}
}
private:
};
class mcu1_Usart : public Usart
{
public:
mcu1_Usart(){}
~mcu1_Usart(){}
struct config
{
uint32_t pin1;
uint32_t pin2;
uint32_t pin3;
uint32_t pin4;
};
virtual int configure(void* hw_args)
{
config* conf = (config*)hw_args;
// do hardware stuff with config
return 0;
}
};
class mcu2_Usart : public Usart
{
public:
mcu2_Usart(){}
~ mcu2_Usart(){}
struct config
{
uint32_t pin1;
uint32_t pin2;
uint32_t pin3;
uint32_t pin4;
uint32_t pin5;
};
virtual int configure(void* hw_args)
{
config* conf = (config*)&hw_args;
// do hardware stuff with config
return 0;
}
};
int main()
{
Usart _usart;
mcu1_Usart::config conf;
_usart.configure((void*)conf);
}
This won't compile. It says it can't convert void* to mcu1_Usart::config. Is there a better way to do this? I really want this to pass/fail at compile time, so using a function pointer as the config init is less than optimal here, but if there's no way to do this in C++ I understand.
Edit: I forgot to say &conf instead of conf. So this does compile. HOWEVER, I would like to know if there is a better way of doing this in C++ because this way is rather unsafe.