How to check for the existence of a subscript operator?

后端 未结 2 1901
情歌与酒
情歌与酒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-14 03:45

    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

提交回复
热议问题