How can I make compile time assertions without C++11

前端 未结 3 2011
囚心锁ツ
囚心锁ツ 2021-02-06 00:10

In a job interview, I was asked to write a metafunction that determined whether a type was a pointer. This is what I presented:

template 
struc         


        
3条回答
  •  滥情空心
    2021-02-06 00:36

    There are different approaches, a common one trying to typedef an invalid type:

    #define static_assert(condition) \
            typedef char assert ## __LINE__ [((condition)?1:-1)]
    

    This can be used in mostly any context and will trip the compiler if the condition is false, since it would try to typedef an invalid type (array of negative number of elements). It can be used in different contexts:

    // namespace level:
    static_assert(sizeof(int)==4);
    struct type {
       // class level:
       static_assert(sizeof(int)==4);
       void f() {
           // function level
           static_assert(sizeof(int)==4);
       }
    };
    

提交回复
热议问题