类成员参数中的Constexpr

Constexpr in class member parameters

本文关键字:Constexpr 参数 成员      更新时间:2023-10-16

我想在类声明的各个部分的std::array的模板参数中指定一个变量,比如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};
};

因此,如果我需要更改常量,我不必在不同的地方多次更改它。显然,上面不是constexpr的工作方式。。。我还尝试过使用公共成员变量而不是函数,但仍然失败。我得到编译器错误:

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

我知道#define语句可以工作,但我希望将其封装在类中。有什么建议吗?

我没能像最初想要的那样在类中使用constexpr。最终,我只在类外放置了一个constexpr,并将两者封装在命名空间中以完成封装。