How to check if a template argument is a std::vector<T>::iterator
?
For void type, we have std::is_void. Is there something like that for std::vector<T>::iterator
?
You could create a trait for that:
#include <vector>
#include <list>
#include <type_traits>
template <class T, class = void>
struct is_vector_iterator: std::is_same<T, std::vector<bool>::iterator> { };
template <class T>
struct is_vector_iterator<T, decltype(*std::declval<T>(), std::enable_if_t<!std::is_same<T, std::vector<bool>::iterator>::value>())>: std::is_same<T, typename std::vector<std::decay_t<decltype(*std::declval<T>())>>::iterator> { };
int main() {
static_assert(is_vector_iterator<std::vector<int>::iterator>::value, "Is not a vector iterator");
static_assert(is_vector_iterator<std::vector<bool>::iterator>::value, "Is not a vector iterator");
static_assert(!is_vector_iterator<std::list<int>::iterator>::value, "Is a vector iterator");
static_assert(!is_vector_iterator<std::list<int>::iterator>::value, "Is a vector iterator");
}
[live demo]
An alternative solution also using std::iterator_traits:
#include <iostream>
#include <vector>
#include <list>
template <typename T>
struct is_vector_iterator
{
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(
typename std::enable_if<
std::is_same<T, typename std::vector<typename C::value_type>::iterator>::value
>::type*);
template <typename>
static no& test(...);
static const bool value = sizeof(test<T>(nullptr)) == sizeof(yes);
};
int main() {
std::cout << is_vector_iterator<int>::value << std::endl;
std::cout << is_vector_iterator<int*>::value << std::endl;
std::cout << is_vector_iterator<std::list<int>::iterator>::value << std::endl;
std::cout << is_vector_iterator<std::vector<int>::iterator>::value << std::endl;
return 0;
}
live demo
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