static if in plain c++?

后端 未结 4 1192
轻奢々
轻奢々 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:34

    Quoting @JohannesSchaubLitb

    with my static_if that works on gcc one can do it :)
    in some limited fashion

    (see also here)

    This trick involves a specific GCC interpretation of the specs on Lambdas in C++11. As such, it will (likely) become a defect report against the standard. This will lead to the trick no longer working in more recent version of GCC (it already doesn't work in 4.7).

    See the comment thread below for some more details from Johanness

    http://ideone.com/KytVv:

    #include 
     
    namespace detail {
    template
    struct call_if { template void operator<<(F) { } };
     
    template<>
    struct call_if {
      template
      void operator<<(F f) { f(); }
    };
    }
     
    #define static_if(cond) detail::call_if() << [&]
     
    template
    void f(T t) {
      static_if(C) {
        t.foo();
      };
    }
     
    int main() {
      f(42);
    }
    

提交回复
热议问题