I want to have some classes that would contain arrays of different sizes. I want this to be statically allocated because it is intended for an embedded system. The only good solution I can think of is using templates.
However, I want to use the same class type to access those objects.
This is my solution so far.
class Base
{
public:
Base(char* _data, int _size) :
data(_data), size(_size) {}
char* getData(void)
{
return data;
}
int getSize(void)
{
return size;
}
protected:
char* const data;
const int size;
};
template <int sz>
class Foo : public Base
{
public:
Foo() : Base(dataBuff, sizeof(dataBuff)) {}
private:
char dataBuff[sz];
};
// Here I can access every template that inherits Base class
void printFoo(Base* base)
{
std::cout << base->getData() << std::endl;
std::cout << "size is " << base->getSize() << std::endl;
}
int main(void)
{
Foo<20> foo;
char* data = foo.getData();
strcpy(data, "Hello world");
printFoo(&foo);
return 0;
}
Of course the reason for this is to have more methods in the base class for appending deleting and searching for data.
Is this something valid? This is something very basic.
Can I have a better solution?
EDIT: Fixed bug (typo).
std::array? If that's not available in your embedded environment, then perhaps it is better to reimpkement it, so you can writearray<char, 20> foo;\$\endgroup\$std::arrayis suitable without adding too much overhead (program memory, RAM etc..). I'll look at it for sure! Thank you for your comment! \$\endgroup\$(char*)& dataBuff: Don't use C cast it says I know better than the compiler (which is usually not the case). It gets rid of your error message but the problem is still there. \$\endgroup\$