What do compilers do with compile-time branching?

前端 未结 5 1105
生来不讨喜
生来不讨喜 2020-11-28 07:23

EDIT: I took the \"if/else\" case as an example that can sometimes be resolved at compile time (eg when static values are involved, cf

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:46

    Credit to @MooingDuck and @Casey

    template
    decltype(auto) if_else_impl(std::true_type, FN1 &&fn1, FN2 &&, Args&&... args)
    {
        return fn1(std::forward(args)...);
    }
    
    template
    decltype(auto) if_else_impl(std::false_type, FN1 &&, FN2 &&fn2, Args&&... args)
    {
        return fn2(std::forward(args)...);
    }
    
    #define static_if(...) if_else_impl(__VA_ARGS__, *this)
    

    And ussage as simple as:

    static_if(do_it,
        [&](auto& self){ return 1; },
        [&](auto& self){ return self.sum(2); }
    );
    

    Works as static if - compiler go only to "true" branch.


    P.S. You need to have self = *this and make member calls from it, due to gcc bug . If you'll have nested lambda calls you can't use this-> instead of self.

提交回复
热议问题