gpt4 book ai didi

c++ - 模板类构造函数不工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:32 50 4
gpt4 key购买 nike

来 self 的其他问题 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*> >'

最佳答案

正如您已经发现的,如果您在另一个模板类中编写模板类,则必须为模板参数指定不同的名称:

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

is_same的特化中,指定特化类名时必须使用相同的类型(也可以命名为U ,但在所有三个地方使用相同的名称:在模板参数列表中以及在专用类名称中):

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

此外,如评论中所述,您应该将这些辅助类设为 struct 而不是 class;那么你不必写public:

关于c++ - 模板类构造函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16626840/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com