gpt4 book ai didi

C++ 模板类重载 [] 运算符

转载 作者:行者123 更新时间:2023-11-30 04:26:24 24 4
gpt4 key购买 nike

我想根据模板参数重载模板类的 [] 运算符。像这样:

template<
typename T,
template<typename> class Property,
template<typename> class Key1,
template<typename> class Key2>
class a_map
{
public:
const Property<T>& operator[](const Key1<T>& k) const
{ return _values[k.index()]; }
const Property<T>& operator[](const Key2<T>& k) const
{ return _values[k.index()]; }
protected:
std::vector<Property<T> > _values;
};

我会像这样使用这个类:

int main()
{
a_map<float, prop, key_a, key_b> pm;
}

基本上我希望能够访问 _values 中的元素 vector 而不必担心 Key类型。重要的是他们有一个 index()成员(member)。

但是我得到以下错误

error C2535: 'const Property &a_map::operator [](const Key1 &) const' : member function already defined or declared

即使key_akey_b是两个完全不同的 类型 类模板。

我错过了什么吗?编译器是否害怕在某些情况下Key1<T>Key2<T>可能实际上是同一类型?

编辑这些是 main 中使用的类模板

template<typename T>
struct prop
{
T weight;
T height;
};


template<typename T>
class key_a
{
public:
int index() { return _i; }
private:
int _i;
};

template<typename T>
class key_b
{
public:
int index() { return 3; } // Always return 3

编辑我正在使用 MVC++ 2008 编译器。

最佳答案

既然你的两个 operator[] 除了参数类型之外都是相同的,为什么不对它们进行模板化呢?

    template <typename TT>
const Property<T>& operator[](const TT& k) const
{
return _values[k.index()];
}

关于C++ 模板类重载 [] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595810/

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