从std容器复制frm任意源对象 [英] Copying from std container frm arbitrary source object

查看:146
本文介绍了从std容器复制frm任意源对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个只读迭代器,它允许我更方便地使用它在for循环,然后使用std迭代器,类似于使用FOREACH(不太好,但足够好):)

I created a read only iterator which allows me to use it in a for loop more conveniently then with the std iterators, similar to what boost does with the FOREACH (not as good but good enough :))

现在看起来像这样:

for(ReadOnylIterator<MyClass *> class = parent.getIterator(); class.end(); ++class)
   class->function();

我现在的问题是,我必须在父实现一个函数返回迭代器。由于std容器具有相同的语法,我想知道是否可以在接受任何std ::容器并创建副本本身的Iterator上定义一个复制构造函数/赋值运算符,而不是要求返回

The problem that I have now is, that I must implement a function on the parent which returns the iterator. Since the std containers have all the same syntax, I was wondering if it is possible to define a copy constructor/assignment operator on the Iterator that accepts any of the std:: containers and creates the copy itself, instead of requiring the class to return it.

当然,我想避免自己定义所有的,因为它们有很多:

Of course I want to avoid having to define all of them myself like as there are lots of them:

ReadOnlyIterator<T> &operator=(std::list<T> const &v)
ReadOnlyIterator<T> &operator=(std::vector<T> const &v)
...

有办法吗?当我看向量的源,我没有看到一个共同的基类,所以我认为它可能是不可能的。

Is there a way to do this? When I look at the source of the vector I don't see a common base class, so I think it might not be posssible.

我不明白为什么赋值运算符不起作用。

I don't understnad why the assignment operator doesn't work.

在我的代码中,我测试如下:

In my code I test it like this:

std::vector<SimpleClass *>t;
ReadOnlyIterator<SimpleClass *> &it = t;

我得到

error C2440: 'initializing' : cannot convert from 'std::vector<_Ty>' to 'ReadOnlyIterator<T> &'


推荐答案

如果我正确理解,工作:

If I understand you correctly, this should work:

#include <type_traits>

template <typename Container>
typename std::enable_if<std::is_same<T, typename Container::value_type>::value, ReadOnlyIterator<T>&>::type operator= (const Container &v);

上述代码使用C ++ 11。如果您无法访问,可以使用Boost的等效功能。

The above code uses C++11. If you don't have access to that, you could use the equivalent functionality from Boost.

Live example

如果您既不能使用C ++ 11也不能使用Boost,你可以自己编写必要的类:

In case you can use neither C++11 nor Boost, you can code the necessary classes yourself:

template <typename T, typename U>
struct is_same
{
    enum { value = 0 };
};

template <typename T>
struct is_same<T, T>
{
    enum { value = 1 };
};

template <bool, typename>
struct enable_if
{};

template <typename T>
struct enable_if<true, T>
{
    typedef T type;
};

要在构造函数中使用它,请如下定义:

To use this in a constructor, define it like this:

template <typename Container>
ReadOnlyIterator(const Container &v, typename enable_if<is_same<T, typename Container::value_type>::value, void>::type * = 0) {}

实例

这篇关于从std容器复制frm任意源对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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