Std :: array as parameter in virtual function

I want to send std::arrayas a parameter to my virtual function

class Handler:
    {
    public:
        template <std::size_t N>
        virtual void handle(const std::array<char, N>& msg, std::vector<boost::asio::const_buffer>& buffers) = 0;
    };

but gccsaid templates may not be 'virtual'. So how do I pass std::arraymy function?

+4
source share
3 answers

A member function template may not be virtual. See this question .

However, you can create a virtual member function by selecting a std::arrayspecific size by moving Nto Handler:

template <size_t N>
class Handler:
{
public:
    virtual void handle(const std::array<char, N>& msg,
        std::vector<boost::asio::const_buffer>& buffers) = 0;
};

Or simply passing vector<char>in which the context set may make more sense:

class Handler:
{
public:
    virtual void handle(const std::vector<char>& msg,
        std::vector<boost::asio::const_buffer>& buffers) = 0;
};
+5
source

-, std::array - , , . :

virtual void handle(const char* arr, std::size_t sz, std::vector<boost::asio::const_buffer>& buffers) = 0;

template <std::size_t sz>
void handle(const std::array<char, sz>& arr, std::vector<boost::asio::const_buffer>& buffers) {
  handle(sz ? &arr[0] : nullptr, sz, buffers);
}
+2

() :

  • , .

  • ( ) , , .

:

template <std::size_t N>
void handle(const std::array<char, N>& msg, std::vector<boost::asio::const_buffer>& buffers)
{
   // stuff that looks like code
}

. , () N.

:

template <>
void handle(const std::array<char, 10>& msg, std::vector<boost::asio::const_buffer>& buffers)

template <>
void handle(const std::array<char, 20>& msg, std::vector<boost::asio::const_buffer>& buffers)

- ( ). , .

Therefore, in order for them to be virtual, there must be 2 entries in the table of virtual functions.

This, for example, will work:

class Handler:
    {
    public:
        virtual void handle(const std::array<char, 10>& msg, std::vector<boost::asio::const_buffer>& buffers) = 0;

        virtual void handle(const std::array<char, 20>& msg, std::vector<boost::asio::const_buffer>& buffers) = 0;

        // and so on for every value on N you need.
    };
0
source

Source: https://habr.com/ru/post/1584898/


All Articles