Enforcing function contract at compile time when possible

后端 未结 3 1229
一生所求
一生所求 2021-02-02 00:12

(this question was inspired by How can I generate a compilation error to prevent certain VALUE (not type) to go into the function?)

Let\'s say, we have a single-argument

3条回答
  •  暖寄归人
    2021-02-02 01:01

    It's not perfect and it requires us to use arguments in two different places, but it 'works':

    template
    int foo(int arg = 0) {
        static_assert(N != 5, "N cannot be 5!");
        int* parg;
        if (arg != 5) {
            parg = &arg;
        }
    
        return *parg;
    }
    

    We can call it like so:

    foo<5>();   // does not compile
    foo(5);     // UB
    foo<5>(5);  // does not compile
    foo<5>(10); // does not compile
    foo<10>(5); // UB
    foo();      // fine
    foo<10>();  // fine
    foo(10);    // fine
    

提交回复
热议问题