1

I'd like to specify a variable in the template parameters of std::array in various parts of my class declaration like so:

class SetAngles
    {
    public:
        constexpr int txSize() const { return 19; }
        constexpr int rxSize() const { return ack.size(); }

        void txParse(std::array<uint8_t, txSize()>& packet)
        {
            ...
        }

    private:
        std::array<uint8_t, txSize()> txPacket = {0xFA, 0x0E, 0x11, 0x00, 0x00, 0x00, 0x00, 
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
};

So I don't have to change a constant a whole bunch of times in various places if I need to change it. Apparently what's above isn't how constexpr works... I have also tried using a public member variable instead of a function, still fails. I get the compiler error:

cannot call member function ‘constexpr int GimbalPacket::SetAngles::txSize() const’ without object

I know a #define statement could work, but I was hoping to keep this encapsulated within the class. Any suggestions on how to do this?

  • 1
    make `txSize()` `static` (if you can) – max66 Jul 19 '18 at 17:16
  • 1
    It seems like `txSize()` should return `txPacket'`s size instead of the other way around. – François Andrieux Jul 19 '18 at 17:20
  • `static member function ‘static constexpr int GimbalPacket::SetAngles::txSize()’ cannot have cv-qualifier` – Andrew Loomis Jul 19 '18 at 17:23
  • [This answer](https://stackoverflow.com/a/41680038/7359094) may be useful. – François Andrieux Jul 19 '18 at 17:23
  • 1
    @AndrewLoomis `static` members can't be `const` because there is no `this` pointer to make `const`. – François Andrieux Jul 19 '18 at 17:24
  • Thanks, I've removed const, added static to txSize(), and now make txSize return txPacket.size(). Now I'm getting this error: `‘static constexpr int GimbalPacket::SetAngles::txSize()’ called in a constant expression before its definition is complete` – Andrew Loomis Jul 19 '18 at 17:42
  • That won't work. A static member function cannot read txPacket (a non-static member). Besides that, you want to use txSize() to determine the size for the array and then use the array's size to return in txSize()? That's a loop, which is why you are getting the error about the definition being incomplete. – Martijn Otto Jul 19 '18 at 18:27

1 Answers1

1

I wasn't able to use constexpr within the class as I initially wanted to. Ended up just putting a constexpr outside the class and wrapping both in a namespace to accomplish the encapsulation.