Is There Anything Like a Templatized Case-Statement

后端 未结 5 975
没有蜡笔的小新
没有蜡笔的小新 2020-12-16 18:18

So I have this really ugly code:

template 
std::conditional_t

        
5条回答
  •  南笙
    南笙 (楼主)
    2020-12-16 18:19

    A type tag:

    templatestruct tag{using type=T;};
    

    void_t (coming in C++17 to a compiler near you):

    templatestruct voider{using type=void;};
    templateusing void_t=typename voider::type;
    

    enable_first_t takes a pack of std::enable_if (note the lack of _t), and returns the first that passes the test. You can use tag to replace std::enable_if:

    templatestruct has_type:std::false_type{};
    templatestruct has_type>:std::true_type{};
    
    namespace details {
      template
      struct enable_first {};
      template
      struct enable_first{} >, T0, Ts... >:enable_first {};
      template
      struct enable_first{} >, T0, Ts...>:T0 {};
    }
    
    templateusing enable_first_t=typename details::enable_first::type;
    
    template
    using result = enable_first_t<
      std::enable_if,
      std::enable_if,
      std::enable_if,
      tag // default
    >;
    

    this behaves a lot like a switch, but the statements are full boolean expressions.

    live example

提交回复
热议问题