Is it possible to prevent omission of aggregate initialization members?

前端 未结 5 1937
孤城傲影
孤城傲影 2021-02-05 00:24

I have a struct with many members of the same type, like this

struct VariablePointers {
   VariablePtr active;
   VariablePtr wasactive;
   VariablePtr filename;         


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-05 00:41

    Here is a trick which triggers a linker error if a required initializer is missing:

    struct init_required_t {
        template 
        operator T() const; // Left undefined
    } static const init_required;
    

    Usage:

    struct Foo {
        int bar = init_required;
    };
    
    int main() {
        Foo f;
    }
    

    Outcome:

    /tmp/ccxwN7Pn.o: In function `Foo::Foo()':
    prog.cc:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x12): undefined reference to `init_required_t::operator int() const'
    collect2: error: ld returned 1 exit status
    

    Caveats:

    • Prior to C++14, this prevents Foo from being an aggregate at all.
    • This technically relies on undefined behaviour (ODR violation), but should work on any sane platform.

提交回复
热议问题