gpt4 book ai didi

c++ - 从模板方法参数的返回值隐式转换

转载 作者:行者123 更新时间:2023-11-28 05:39:11 35 4
gpt4 key购买 nike

我正在尝试根据分配的 ID 为存储在 vector 中的元素构建自定义索引,该索引不会更改。索引可能会发生变化,因此索引会发生变化。

模板结构如下:

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

private:
QVector<Element> data;
};

所以在这个类中,我将任意类型的元素存储在一个 vector 中。为了检索它们,我使用了一个带有 Index 参数的 get 方法。 Index 必须是整数类型但我不能直接使用 int 因为我将把它用于 QFile 存储以及使用 qint64 作为索引,因此模板 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 仅存储 Indexe 的 vector (它是一个哈希表,使用 ID 到达正确的位置)它需要一种方法来检查给定插槽中的 ID 是否与 StoreID 检索模板参数匹配。

那么用法将是:

using TheID = int;
using TheIndex = int;
using TheStore = MyStore<MyElement<ID>, Index>;

TheStore store;
MyIndex<TheID, TheIndex, TheStore, &TheStore::get> idx;

MyIndex 的实例化失败,因为编译器没有找到最后一个参数的匹配项,因为它提示它无法将任何内容转换为 ID,尽管我确实提供了隐式转换从 MyElementID

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

最佳答案

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

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

其中类型的成员函数指针

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

是必需的。自 intMyElement<int>是不同的类型,如果没有隐式或显式转换,它们是不兼容的,即使前者的返回类型可以转换为后者的返回类型。

关于c++ - 从模板方法参数的返回值隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541997/

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