mercredi 25 novembre 2015

How to use static_assert used with a member initilizer list

I would want to use static_assert to enforce various limitations on configuration of my class. Earlier I would just use an enum and only allow a single constructor which requires said enum to enforce a limit on my class. This worked fine if I have something like below and the range is from 0 to 4, but once I have a range of 0 to 500 then using an enum becomes unwieldy.

Some_Class.h

class Some_Class {
    public:
        Some_Class(const unsigned int param);
    private:
        const unsigned int member_param;
};

Some_Class.cpp

Some_Class::Some_Class(const unsigned int param) : member_param(param) {
    static_assert(member_param < 500, "Param must be less than 500.");
};

Main.cpp

Some_Class foo4(125); // OK
Some_Class foo5(500); // Should fail at compile time.

This is what GCC throws at me when compiling with C++14:

1>  Some_Class.cpp: In constructor 'Some_Class::Some_Class(unsigned int)':
1>C:\some_path\Some_Class.cpp(3,2): error : non-constant condition for static assertion
1>    static_assert(member_param < 500, "Param must be less than 500.");
1>    ^
1>C:\some_path\Some_Class.cpp(3,2): error : use of 'this' in a constant expression

Aucun commentaire:

Enregistrer un commentaire