Is there any situation where you wouldn't want include guards?

前端 未结 6 768
北海茫月
北海茫月 2021-01-11 22:08

I know why include guards exist, and that #pragma once is not standard and thus not supported by all compilers etc.

My question is of a different kind:<

6条回答
  •  自闭症患者
    2021-01-11 22:25

    @sbi already talked about code generation, so let me give an example.

    Say that you have an enumeration of a lot of items, and that you would like to generate a bunch of functions for each of its elements...

    One solution is to use this multiple inclusion trick.

    // myenumeration.td
    MY_ENUMERATION_META_FUNCTION(Item1)
    MY_ENUMERATION_META_FUNCTION(Item2)
    MY_ENUMERATION_META_FUNCTION(Item3)
    MY_ENUMERATION_META_FUNCTION(Item4)
    MY_ENUMERATION_META_FUNCTION(Item5)
    

    Then people just use it like so:

    #define MY_ENUMERATION_META_FUNCTION(Item_) \
      case Item_: return #Item_;
    
    char const* print(MyEnum i)
    {
      switch(i) {
        #include "myenumeration.td"
      }
    
      __unreachable__("print");
      return 0; // to shut up gcc
    }
    
    #undef MY_ENUMERATION_META_FUNCTION
    

    Whether this is nice or hackish is up to you, but clearly it is useful not to have to crawl through all the utilities functions each time a new value is added to the enum.

提交回复
热议问题