模板方法参数的返回值

时间:2016-05-31 09:33:40

标签: c++ templates

我正在尝试根据不会更改的已分配ID构建存储在向量中的元素的自定义索引。索引可能会改变,因此索引。

模板结构如下:

template<typename Element, typename Index>
class MyStore
{
public:
    //...
    Element get(Index index) const { return data.at(index); }

private:
    QVector<Element> data;
};

所以在这个类中我将任意类型的元素存储在向量中。要检索它们,我使用get方法,该方法需要Index个参数。 Index必须是整数类型,但我不能直接使用int,因为我也会将此用于QFile存储,并使用qint64作为索引,因此模板{{ 1}}。

Index

因此 template<typename ID> class MyElement { public: //... operator ID() const { return m_ID; } private: ID m_ID; }; 使用MyElement作为标识符,并且可以隐式转换为它。没什么好看的。最后:

ID

所以template<typename ID, typename Index, typename Store, ID (Store::*get)(Index) const> class MyIndex { public: //... private: Store *m_Store; QVector<Index> m_Index; }; 只存储MyIndex s的向量(它是一个使用Indexe到达正确插槽的哈希表),它需要一种方法来检查因此,{?1}}和ID视网膜模板参数匹配给定广告位中的ID

然后使用:

Store

ID的实例化失败,因为编译器找不到最后一个参数的匹配项,因为它抱怨它无法将任何内容转换为using TheID = int; using TheIndex = int; using TheStore = MyStore<MyElement<ID>, Index>; TheStore store; MyIndex<TheID, TheIndex, TheStore, &TheStore::get> idx; ,尽管我提供了来自MyIndex的隐式转换到ID

有没有办法让这项工作或我需要提供一个确切的方法返回MyElement(而不是其他类型,即使它可以隐式转换为ID){{1第四个参数?

1 个答案:

答案 0 :(得分:1)

函数指针或成员函数指针类型之间不进行转换。即使一个[member]函数指针中的返回类型可以转换为另一个[member]函数指针中的返回类型,它们也是完全不同的实体。您的代码尝试使用

MyElement<int> (MyStore<MyElement<int>, int>::*)(int) const

其中一个类型为

的成员函数指针
int (MyStore<MyElement<int>, int>::*)(int) const

是必需的。由于intMyElement<int>是不同的类型,因此它们在没有隐式或显式转换的情况下是不兼容的,即使前者的返回类型可以转换为后者的返回类型。

相关问题