I'm trying to check if operator []
overloaded in some class. There is my code:
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 {};
But it doesn't work actualy.
I'm trying to write like code witch cheking if class has operator ()
here it's :
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{};
Ok, This code compiles, but how to do the verification exactly in 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 {};
I did it!
#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";
}