How to check for the existence of a subscript operator?

后端 未结 2 1231
离开以前
离开以前 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())[std::declval()] // and use that here
           ),
           class = typename std::enable_if<
             !std::is_void::value
           >::type>
    static std::true_type test(int);
    

    Now your code works as intended.

    Live demo

提交回复
热议问题