lundi 2 novembre 2020

Static polymorphism with constant template

I'd like to have a static polymorphism with the parent class having a template std::array size. This code works fine:

#include <iostream>
#include <array>

using namespace std;

template <size_t size>
class Message
{
  public:
    size_t GetSize() { return size; }
  private:
    std::array<uint8_t, size> data_{};
};

class Command : public Message<12>
{
  public:
    static const size_t kCmdSize{12};
  private:
};

int main()
{
    Command cmd{};
    cout << "Size: " << cmd.GetSize() << endl;
    return 0;
}

But I'm not a huge fan of magic numbers.

Is there any way to use a constant declared in the child class as the parameter to the parent class? Something like that:

class Command : public Message<kCmdSize>
{
  public:
    static const size_t kCmdSize{12};
  private:
};

Using this directly attempts to use a variable from a class that doesn't exist yet. Using C++14.

Aucun commentaire:

Enregistrer un commentaire