检查变量类型是否可迭代? [英] Check if a variable type is iterable?

查看:73
本文介绍了检查变量类型是否可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以检查任意变量类型是否可迭代?

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?

我们在搜索时发现了其他编程语言的技术。

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循环,该类型需要 begin() end()方法定义并返回响应 operator!=
operator ++ 和<$ c $的迭代器c> operator * 。

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

这篇关于检查变量类型是否可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆