How to check for the existence of a subscript operator?

后端 未结 2 1816
情歌与酒
情歌与酒 2021-02-14 03:10

I want to write a type trait which uses SFINAE to check a type for the existence of a subscript expression. My initial attempt below seems to work when the subscript expression

2条回答
  •  遇见更好的自我
    2021-02-14 03:51

    Once you have C++11, it's a lot easier to write type traits... you don't need to use the ellipsis overload trick. You can just use your decltype expression directly with the help of the magical:

    template 
    using void_t = void;
    

    We have our base case:

    template
    struct has_subscript_operator : std::false_type { };
    

    And our expression SFINAE valid case:

    template
    struct has_subscript_operator()[std::declval()])
    >> : std::true_type { };
    

    And then you can write the same alias:

    template 
    using has_subscript_operator_t = typename has_subscript_operator::type;
    

    You can also use @Yakk's favorite method, which given this boilerplate that he copies in every answer:

    namespace details {
      templatestruct voider{using type=void;};
      templateusing void_t=typename voider::type;
    
      templateclass Z, class, class...Ts>
      struct can_apply:
        std::false_type
      {};
      templateclass Z, class...Ts>
      struct can_apply>, Ts...>:
        std::true_type
      {};
    }
    templateclass Z, class...Ts>
    using can_apply=details::can_apply;
    

    You can then simply write properties:

    template 
    using subscript_t = decltype(std::declval()[std::declval()]);
    
    template 
    using has_subscript = can_apply;
    

提交回复
热议问题