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

前端 未结 3 2010
囚心锁ツ
囚心锁ツ 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:41

    I would use BOOST_STATIC_ASSERT. You can look at the code: boost/static_assert.hpp.

    Here's a very simplified version, just to give you an idea:

    #define JOIN(X, Y) DO_JOIN(X, Y)
    #define DO_JOIN(X, Y) X ## Y
    
    template
    struct Static_assert_helper;  // incomplete type
    
    template<>
    struct Static_assert_helper {
        typedef int Type;
    };
    
    #define STATIC_ASSERT(cond) \
        typedef Static_assert_helper<(cond)>::Type JOIN(Static_assert_typedef_, __LINE__)
    

    It can be used in many places (see the documentation for examples).

    (Boost's implementation is more complete, with e.g. a sizeof and an intermediate struct, to give a better error message and be portable on a wide range of compilers.)

提交回复
热议问题