如何检查 class 是否有运算符 []?

how to check if a class has an operator []?

我正在尝试检查 operator [] 是否在某些 class 中超载。有我的代码:

template <class T, class = void>
struct has_operator : std::false_type {};

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

但实际上并没有用。

我正在尝试编写类似代码 检查 class 是否有 operator ()

这里是:

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

template <typename T>
struct callable_without_args<T
          ,std::void_t<decltype(std::declval<T>()())>>
  :std::true_type{};

好的,这段代码编译通过了,但是如何在 main 中准确地进行验证?:


template <class T, class = void>
struct has_operator : std::false_type {};

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

我做到了!

#include <type_traits>
#include <tuple>
#include <vector>


template <class T, class = void>
struct has_operator : std::false_type {};

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


struct T {
    int* arr;
    T(int a) {
        arr = new int[a];
    }
    const int& operator [] (int i) {
        return arr[i];
    }
};

int main() {
    bool test = has_operator<T>::value;

    test == true ? std::cout << "yes" : std::cout << "no";
}

不完全清楚你到底想要什么但是...下面的decltype()是错误的

// ---------------------VVVVVVVVV   Wrong
decltype(std::declval<T>[](int i))

std::declval() 是一个(仅声明的)函数,不接收参数。

也就是说:你必须"call"它,在“<T>”之后添加“()”。

我想你可以试试

// .....................VV  call std::declval   
decltype(std::declval<T>()[0])
// .......................^^^  and invoke operator [] over the retuned object

当 class Toperator[] 接受整数值时,这应该有效。

如果 operator[] 不接受整数值(例如:std::map 的键与 int 不兼容)但想要另一种类型的值,比如类型 U,你可以试试另一个 std::declval()

// ........................VVVVVVVVVVVVVVVVV   U value
decltype(std::declval<T>()[std::declval<U>()])