從我這裏的其他問題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