Enforcing function contract at compile time when possible

后端 未结 3 1228
一生所求
一生所求 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:11

    gcc/clang/intel compilers support __builtin_constant_p, so you can use something like that:

    template 
    int foo_ub(int arg) {
        static_assert(D != 5, "error");
        int* parg = nullptr;
        if (arg != 5) {
            parg = &arg;
        }
    
        return *parg;
    }
    
    #define foo(e) foo_ub< __builtin_constant_p(e) ? e : 0 >(e)
    

    these statements produce compile time error:

    • foo(5)
    • foo(2+3)
    • constexpr int i = 5; foo(i);

    while all others - runtime segfault (or ub if no nullptr is used)

提交回复
热议问题