检查一个变量是迭代?
有没有什么办法来检查,如果一个任意变量类型是可迭代?
Is there any way to check if an arbitrary variable type is iterable?
所以要检查它是否索引元素或其实我可以遍历它的孩子吗? (例如使用的foreach?)
So to check if it has indexed elements or I can actually loop over it's children? (Use foreach for example?)
是否有可能创建一个通用模板?
Is it possible to create a universal template for that?
我已经找到了其他编程语言技术,同时寻找它。但仍然必须找出如何做到这一点的C ++。
I've found techniques for other programming languages while searching for it. Yet still have to find out how to do this in C++.
这取决于你所说的迭代是什么。这是C ++中的松散的概念,因为你可以在许多不同的方式实现迭代器。
It depends on what you mean by "iterable". It is a loose concept in C++ since you could implement iterators in many different ways.
如果按的foreach
你指的是C ++ 11的射程为基础的for循环,类型的需求开始()
定义和端()
方法,并返回到运营商应对迭代器!=
,符++
和运算符*
。
If by foreach
you're referring to C++11's range-based for loops, the type needs begin()
and end()
methods to be defined and to return iterators that respond to operator!=
,
operator++
and operator*
.
如果你的意思是Boost的BOOST_FOREACH帮手,后来看到 BOOST_FOREACH扩展。
If you mean Boost's BOOST_FOREACH helper, then see BOOST_FOREACH Extensibility.
如果你的设计,你有一个共同的接口,所有的迭代容器继承,那么你可以使用C ++ 11的的的std :: is_base_of :
If in your design you have a common interface that all iterable containers inherit from, then you could use C++11's std::is_base_of:
struct A : IterableInterface {}
struct B {}
template <typename T>
constexpr bool is_iterable() {
return std::is_base_of<IterableInterface, T>::value;
}
is_iterable<A>(); // true
is_iterable<B>(); // false