Based on answers here and here I am trying to use the following
template <typename T>
using operator_square_brackets = decltype(&T::operator[]);
It fails on visual studio with
error C2760: syntax error: expected ')' not ']'
Any ideas on how to fix this?
If you want to detect whether a type has a certain function or overloaded operator you have to call that function or operator. This is important because you might have several overloads of a function or operator and overload resolution always depends on the caller.
Here is a small example, based on CppCon 2014: Walter E. Brown "Modern Template Metaprogramming: A Compendium, Part II" on how to detect operator[]
in a type.
I have no idea why VC is giving you such a weird error which looks more like a parsing error. I would have expected something like »reference to overloaded function could not be resolved; did you mean 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, "!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With