Use static_assert to check types passed to macro

前端 未结 5 1528
再見小時候
再見小時候 2020-12-09 08:30

I unfortunately have several macros left over from the original version of my library that employed some pretty crazy C. In particular, I have a series of macros that expect

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-09 09:00

    Disclaimer: This is a bad answer, there are definitely far better solutions. Just an example :)

    It is bound to be already implemented, but it's trivial to implement yourself;

    template  struct CheckSameType; //no definition
    template  struct CheckSameType{}; //
    
    template 
    AssertHasType(T2)
    {
       CheckSameType tmp; //will result in error if T1 is not T2
    }
    

    To be used like this:

    AssertHasType(retval);
    

    Alternative (suggested by GMan):

    template  struct SameType
    {
        enum{value = false};
    }
    template  struct SameType
    {
        enum{value = true};
    }; 
    

    To be used like

    static_assert(SameType::value);
    

提交回复
热议问题