Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use templated class without template

I have class like this:

template<size_t MAX_SIZE>
struct Buffer{
   size_t size;
   char data[MAX_SIZE]; // this must be inside the struct itself
   constexpr static size_t max_size = MAX_SIZE;
};

I need to be able to pass this class to function that shouldn't use template, currently I am doing something like this:

void process(size_t &size, char *data, size_t max_size);

int main(){
   Buffer<1024> b;
   process(b.size, b.data, b.max_size);
}

Is there any better way to do the same? I can think about base class, and pass by reference, but it gets too complicated to be correct.

(This is not actual code, please do not pay attention if there are syntax errors.)

like image 389
Nick Avatar asked Apr 08 '26 18:04

Nick


1 Answers

I would use a wrapper-method ...

template<size_t MAX_SIZE>
void process(Buffer<MAX_SIZE>& buffer)
{
    process(buffer.size, buffer.data, buffer.max_size);
}

... and then just call ...

int main()
{
    Buffer<1024> buffy;
    process(buffy);
    return 0;
}
like image 157
CppChris Avatar answered Apr 10 '26 06:04

CppChris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!