本文介绍了如何检查任意类型是否是迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这与完全重复,除了接受的答案是错误的,所以我再次询问:
This is an exact duplicate of this question, except that accepted answer is wrong, so I ask it again:
如何正确检查给定类型 T
是一个迭代器?
How do you correctly check to see if a given type T
is an iterator?
我尝试解决它:
// Assume enable_if and is_same are defined
// (hoping for a solution that works for C++03 too)
template<class T>
class is_iterator
{
static char (&test(...))[2];
template<class U>
static typename std::enable_if<
!std::is_same<
typename std::iterator_traits<T>::value_type,
void
>::value,
char
>::type test(U);
public:
static bool const value = sizeof(test(0)) == 1;
};
struct Foo { };
int main()
{
return is_iterator<Foo>::value;
}
恰好失败:
因为 iterator_traits
正在查找 value_type
的定义 Foo
,这显然不存在。
because iterator_traits
is looking for a definition of value_type
in Foo
, which (obviously) doesn't exist.
我 __ if_exists
是Visual C ++的一种可能性,但我正在寻找一个可移植的解决方案。
I am aware that __if_exists
is a possibility on Visual C++, but I'm looking for a portable solution.
推荐答案
这样的东西呢?
template<typename T, typename = void>
struct is_iterator
{
static constexpr bool value = false;
};
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type>
{
static constexpr bool value = true;
};
例如:
#include <iostream>
#include <type_traits>
#include <vector>
template<typename T, typename = void>
struct is_iterator
{
static constexpr bool value = false;
};
template<typename T>
struct is_iterator<T, typename std::enable_if<!std::is_same<typename std::iterator_traits<T>::value_type, void>::value>::type>
{
static constexpr bool value = true;
};
int main()
{
static_assert(!is_iterator<int>::value, "ass");
static_assert(is_iterator<int*>::value, "ass");
static_assert(is_iterator<std::vector<int>::iterator>::value, "ass");
}
这篇关于如何检查任意类型是否是迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!