从我这里的其他问题Copying from std container frm arbitrary source object我设法让模板几乎在MSVC下工作。不幸的是,编译器崩溃,添加了一个构造函数来接受所有类型的std容器,而我的真实项目仍然在gcc中。现在,当我在gcc中使用此模板时,出现了几个我不知道如何解决的错误。模板类构造函数不工作
template <class T> class ReadOnlyIterator
{
public:
template <typename V, typename U>
struct is_same
{
enum { value = 0 };
};
template <typename V>
struct is_same<V, V>
{
enum { value = 1 };
};
template <bool, typename>
struct enable_if
{};
template <typename V>
struct enable_if<true, V>
{
typedef V type;
};
template <typename Container>
typename enable_if<
is_same<T, typename Container::value_type>::value, ReadOnlyIterator<T>&>::type operator= (const Container &v)
{
return *this;
}
template <typename Container>
ReadOnlyIterator(const Container &v, typename enable_if<is_same<T, typename Container::value_type>::value, void>::type * = 0)
{
mVector = v;
mBegin = mVector.begin();
}
};
我的目标是让分配是这样的:
std::vector<SimpleClass *>v;
std::list<SimpleClass *>l;
ReadOnlyIterator<SimpleClass *> t0 = v;
ReadOnlyIterator<SimpleClass *> &t1 = v;
ReadOnlyIterator<SimpleClass *> t2 = ReadOnlyIterator<SimpleClass *>(v);
ReadOnlyIterator<SimpleClass *> t3 = l;
t0 = v;
t0 = l;
我更新了上面的代码并恢复我申请了错误的变化。所以,现在我只能拿到原来的问题,我试图修复:
ReadOnlyIterator<SimpleClass *> &t1 = v;
导致:
invalid initialization of reference of type 'ReadOnlyIterator<SimpleClass*>&' from expression of type 'std::vector<SimpleClass*, std::allocator<SimpleClass*> >'
请注意,在你之前的问题中,我使用'struct'而不是'class'作为助手('struct'默认情况下具有公共访问权限,'class'具有私有权限),并且我将它们命名为namespace-scope,而不是嵌套在'ReadOnlyIterator'中。 – Angew
好的。我改回了它,但它仍然不起作用,因为我得到了与上面相同的错误。 – Devolus
请参阅leemes的答案。您至少可以正确复制以前的答案。 – Angew