static if in plain c++?

后端 未结 4 1196
轻奢々
轻奢々 2021-02-13 20:13

Problem in short:
How could one implement static if functionality, proposed in c++11, in plain c++ ?

History and original prob

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-13 20:32

    Most compilers do constant folding and dead code removal, so if you write a regular if statement like this:

    enum SenderType { Single, Double };
    template
    class Sender
    {
       void sendMessage(...)
       {
          // do stuff
          if ( T == Single )
          {
             sendMessage(...);
          }
       }
    };
    

    The if branch will get removed when the code is generated.

    The need for static if is when the statements would cause a compiler error. So say you had something like this(its somewhat psuedo code):

    static if (it == random_access_iterator)
    {
        it += n;
    }
    

    Since you can't call += on non-random access iterators, then the code would always fail to compile with a regular if statement, even with dead code removal. Because the compiler still will check the syntax for before removing the code. When using static if the compiler will skip checking the syntax if the condition is not true.

提交回复
热议问题