c++ - C++ 中类似 Iterable 的行为是否可以实现?

标签 c++

Java 允许类显示 Iterable类型,以便客户端可以遍历某些实例的数据集合,如下所示:

public class MyClass
{
    private ArrayList<String> strings;
    private ArrayList<Integers> ints;
    public MyClass() { /* generate data ... */ }
    public Iterable<String> allStrings() {return strings;}
    public Iterable<Integer> allInts() {return ints;}
}

这一直让我觉得“干净”,因为它保持封装,允许我更改 ArrayList s 至 LinkedList如果我愿意并且在 for(String s : myClassInstance.allStrings()) //... 等结构中对客户来说仍然很方便.

然而,在 C++ 中,如果我想让客户端使用我的 for-loop , 在没有 Iterable 的情况下,我需要返回一个 const vector<T>&或其他,这显然不太好。

定义 template<> begin<my_class> {/*...*/}和 friend 很好,但前提是 my_class有一个集合要迭代。我还能做什么?

最佳答案

只需在 C++ 中制作 Iterable

template<class T, class U>
struct Iterable
{
    T _begin;
    U _end;

    Iterable(T begin, U end)
    : _begin(begin), _end(end)
    {}

    T begin()
    {
        return _begin;
    }

    U end()
    {
        return _end;
    }
};

template<class T, class U>
Iterable<T,U> make_iterable(T t, U u)
{
    return Iterable<T,U>(t, u);
}

struct MyClass 
{
    std::vector<int> _ints;
    std::vector<std::string> _strings;

    auto allInts() -> decltype(make_iterable(_ints.begin(), _ints.end()))
    {
        return make_iterable(_ints.begin(), _ints.end());
    }

    auto allStrings() -> decltype(make_iterable(_strings.begin(), _strings.end()))
    {
        return make_iterable(_strings.begin(), _strings.end());
    }
};

然后像这样使用它

for (auto i : foo.allInts())
{
    cout << i << endl;
}

for (auto i : foo.allStrings())
{
    cout << i << endl;
}

live example

关于c++ - C++ 中类似 Iterable 的行为是否可以实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23400693/

相关文章:

c++ - GLM中的矩阵部门

c++ - 从字符串中替换字符

C++0x "Hello Concurrent World"在 g++/linux 上立即出现段错误?

c++ - 使用 GLM 矩阵和 vector 乘法返回错误结果

c++ - 对通过引用传递给它的第一个元素的数组进行操作

c++ - OpenMP(C/C++) : Efficient way of sharing an unordered_map<string, vector<int>> 和线程之间的 ve​​ctor<int>

C# 相当于 C++ 中的 64 位 unsigned long long

c++ - Very Sleepy 中的颜色含义

c++ - C++ 中的 C 复数?

c++ - operator= 和 C++ 中不继承的函数?