How to check for the existence of a subscript operator?

后端 未结 2 1225
离开以前
离开以前 2021-02-14 02:56

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:44

    SFINAE only works when substitution failure happens in the immediate context. The template parameter Index is already known by the time the member function template test is being instantiated, so instead of substitution failure you get a hard error.

    The trick to working around this is to deduce Index again by adding an additional template type parameter to test and default it to Index.

    template<class T1,
           class IndexDeduced = Index,  // <--- here
           class Reference = decltype(
             (*std::declval<T*>())[std::declval<IndexDeduced>()] // and use that here
           ),
           class = typename std::enable_if<
             !std::is_void<Reference>::value
           >::type>
    static std::true_type test(int);
    

    Now your code works as intended.

    Live demo

    0 讨论(0)
  • 2021-02-14 03:59

    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 <typename... >
    using void_t = void;
    

    We have our base case:

    template<class T, class Index, typename = void>
    struct has_subscript_operator : std::false_type { };
    

    And our expression SFINAE valid case:

    template<class T, class Index>
    struct has_subscript_operator<T, Index, void_t<
        decltype(std::declval<T>()[std::declval<Index>()])
    >> : std::true_type { };
    

    And then you can write the same alias:

    template <class T, class Index>
    using has_subscript_operator_t = typename has_subscript_operator<T, Index>::type;
    

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

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

    You can then simply write properties:

    template <class T, class Index>
    using subscript_t = decltype(std::declval<T>()[std::declval<Index>()]);
    
    template <class T, class Index>
    using has_subscript = can_apply<subscript_t, T, Index>;
    
    0 讨论(0)
提交回复
热议问题