SFINAE: decltype on operator []

Based on the answers here and here I am trying to use the following

template <typename T> using operator_square_brackets = decltype(&T::operator[]); 

Visual Studio crash with

 error C2760: syntax error: expected ')' not ']' 

Any ideas on how to fix this?

+8
c ++ visual-studio sfinae
source share
1 answer

If you want to determine whether a type has a specific function or an overloaded operator, you must call that function or operator. This is important because you can have multiple overloads of a function or statement, and the resolution of the overload always depends on the caller.

Here is a small example based on CppCon 2014: Walter E. Brown, β€œModern Template Metaprogramming: A Collection, Part II,” on how to detect operator[] in a type.

I have no idea why VC is giving you such a strange error that looks more like a parsing error. I would expect something like: a link to an overloaded function could not be resolved; did you intend to call it? "

 #include <string> #include <type_traits> #include <vector> // in C++17 std::void_t template < typename... > using void_t = void; template < typename T, typename Index > using subscript_t = decltype(std::declval<T>()[std::declval<Index>()]); template < typename, typename Index = size_t, typename = void_t<> > struct has_subscript : std::false_type {}; template < typename T, typename Index > struct has_subscript< T, Index, void_t< subscript_t<T,Index> > > : std::true_type {}; struct A { void operator[](size_t) {} }; struct B {}; int main () { static_assert(has_subscript< std::vector<int> >::value == true , "!"); static_assert(has_subscript< std::vector<double> >::value == true , "!"); static_assert(has_subscript< A >::value == true , "!"); static_assert(has_subscript< A, std::string >::value == false, "!"); static_assert(has_subscript< B >::value == false, "!"); static_assert(has_subscript< double[5] >::value == true , "!"); static_assert(has_subscript< double* >::value == true , "!"); static_assert(has_subscript< double >::value == false, "!"); } 
+8
source share

All Articles