Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple sized arrays to virtual method without using templates

So I have a pure virtual class that needs to stay that way. In this class I have or technically need a method that takes in a templatized parameter. Here is the object type for the parameter:

template <int LENGTH>
struct MyStruct
{
  int arr[LENGTH];
};

And here is my method:

template <int LENGTH>
virtual bool send_struct(const MyStruct<LENGTH>& mystruct) = 0;

However, obviously I cannot use a template with a virtual class, the alternative being adding the template to the class, which I also cannot do for my purpose. Is there an alternative to this while keeping my constraints? I need to pass array of different sizes to this method inside my pure virtual class, but I cannot templatize the class.

like image 890
arias_JC Avatar asked Sep 13 '26 10:09

arias_JC


1 Answers

You can't write this, as you know:

template <int LENGTH>
virtual bool send_struct(const MyStruct<LENGTH>& mystruct) = 0;

There is no way to pass through a compile-time LENGTH. But you can pass through a run-time length by type-erasing your container:

virtual bool send_struct(gsl::span<int const> ) = 0;

gsl::span<T> is a non-owning, contiguous container of Ts. It's a view onto an array or a vector or whatever else, which can be a MyStruct<N> too. This type isn't directly constructible from your struct, but it's easy to write a version that is, or to add the necessary members to yours (.data() and .size()) to make it work.

An extremely simple implementation would just be:

class my_span {
private:
    int const* begin_;
    int const* end_;

public:
    template <int L>
    my_span(MyStruct<L> const& ms)
        : begin_(ms.arr)
        , end_(ms.arr + L)
    { }

    int const* begin() const { return begin_; }
    int const* end() const { return end_; }
    int const* data() const { return begin_; }
    size_t size() const { return end_ - begin_; }
};

And now you have a easily overridable virtual function for some non-modifiable container of ints.

like image 84
Barry Avatar answered Sep 14 '26 23:09

Barry



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!