function that takes only literal integers

后端 未结 3 1901
一生所求
一生所求 2021-01-03 22:30

I\'m looking for a way to simulate certain overloaded GCC built-ins in C++. The built-ins are similar to these:

__builtin_foo(char *a, signed int b);
__buil         


        
3条回答
  •  一个人的身影
    2021-01-03 22:37

    Here is a portable C++11 solution so that your function (macro actually, sorry) accepts only integer literals and triggers a compile-time error instead:

    constexpr int operator "" _literal(unsigned long long i)
    {
        return i;
    }
    
    #define m_builtin_foo(integer) builtin_foo(integer ## _literal)
    

    User-defined literals accept only literals (hence their name). Therefore, if you make your macro paste a user-defined literal to what is passed to it, it should only accept the literals accepted by the corresponding user-defined literal.

    However, that's rather ugly and I guess that could be error-prone. Not sure how though.


    @MichaelAnderson pointed in the comments that m_builtin_foo(i+1) would still work. That's right. @Angew suggested wrapping the return type of _literal in a wrapper incompatible with integer arithmetic and adding explicit conversions. He was also right, here is the more complete solution:

    struct wrapper
    {
        constexpr wrapper(int n):
            value{n}
        {}
    
        explicit constexpr operator int() const
        {
            return value;
        }
    
        int value;
    };
    
    constexpr wrapper operator "" _literal(unsigned long long i)
    {
        return { int(i) };
    }
    
    #define m_builtin_foo(integer) builtin_foo(int(integer ## _literal))
    

提交回复
热议问题