6

I'd like to enforce a compile-time constraint about the length of a class static member variable array using static_assert(). However, the length of the variable named lpfilter[] is not known in the declaration in the header, and only known later in the definition. I'm uncertain how best to implement this static_assert so that it may see the static private array length. I have a workaround using a private scoped function to hold static_asserts, but is there a better way? I'm using clang 15 in C++14 mode.

//in header
class test
{ 
private:
    //member constants
    static const float lpfilter[];

    //feels like a workaround
    void testChecker(void);
};
//early in cpp file
const float test::lpfilter[] = {
    #include "a_single_line_lpfilter.csv"
};

I've made a few attempts so far. Each build error makes sense:

//after lpfilter[] definition in cpp file

//error: 'lpfilter' is a private member of 'test'
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//error: redefinition of 'test'
class test
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}

//error: expected unqualified-id
test::static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");

//works, but I'd prefer not to have to use a function to do this
void test::testChecker()
{
static_assert((sizeof(test::lpfilter)/sizeof(test::lpfilter[0])) % 2, "filter length must be even");
}
5
  • 2
    Would a helper friend class bother you less than a helper function? Commented Dec 12, 2022 at 14:43
  • 2
    FWIW I'd just drop the static_assert into one of the constructors. If a constructor is not available I'd place it the main function that accesses the member variable (or closest to it's first logical access). Commented Dec 12, 2022 at 15:15
  • 2
    Why lpfilter must be private static field of test class? IMO simply can be some global constant in anonymous namespace in cpp file.
    – Marek R
    Commented Dec 12, 2022 at 15:24
  • @MarekR: Here, that would probably be an improvement, but there are other reasons (like type completeness) to have a separate definition of what really should be a static data member. Commented Dec 12, 2022 at 19:23
  • Helper friend class does bother me less. Constructors are currently in the header, but could be moved. Type completeness is what I was going for, but static global constant in the cpp is what I would do in C, and will work.
    – rsaxvc
    Commented Dec 13, 2022 at 20:32

0

Browse other questions tagged or ask your own question.