C++嵌套类模板错误C2440 '=' : cannot convert from 'type' to 'same type'

标签 c++ visual-studio templates inner-classes

我在下面的代码中得到 2 个(可能)相同的错误:

Error   C2440   'initializing': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'`
Error C2440 '=': cannot convert from 'HashTable::HashTableEntry *' to 'HashTable::HashTableEntry *'

It occurs in my HashTable class, rehash() function. Here's the code snippet below:

template<class T, class V>
class HashTable {
private:
    template<class T, class V> struct HashTableEntry {
        T key;
        V value;
    };
    ...
    int size;
    int capacity;
    HashTableEntry<T,V>* A;
public:
    // ctor
    HashTable(int cap) :
        size(0), capacity(cap), A(new HashTableEntry<T,V>[cap])
    {
        ...
    }
    ...
    template<typename T, typename V> void rehash()
    {
        ...
        HashTableEntry<T,V>* newMemoryRegion = new HashTableEntry<T,V>[capacity];
        HashTableEntry<T,V>* disposable = A; // FIRST ERROR HERE
        A = newMemoryRegion;                 // SECOND ERROR HERE
        ...
    }
    ...
}

我正在尝试做的(正如您可能意识到的那样)是获取 disposable指向A的内存地址,然后是 A指向newMemoryRegion的地址。

我试过 static_cast<>他们——不好。然后我取出了嵌套类 - 仍然是同样的错误。最后我试了reinterpret_cast<>第一个错误(初始化)消失了,但奇怪的是第二个错误仍然存​​在:

HashTableEntry<T,V>* disposable = reinterpret_cast<HashTableEntry<T, V>*>(A); // no more errors here
A = reinterpret_cast<HashTableEntry<T, V>*>(newMemoryRegion); // SAME SECOND ERROR persists here

为什么会这样?我怎样才能使它工作?

最佳答案

为什么 HashTableEntryrehash() 使用它们自己的参数来模板化,这些参数反射(reflect)了 HashTable 的模板参数?您应该从 HashTableEntryrehash() 中删除模板,让它们继承 HashTable 中的参数:

template<class T, class V>
class HashTable {
private:
    struct HashTableEntry {
        T key;
        V value;
    };
    ...
    int size;
    int capacity;
    HashTableEntry* A;
public:
    // ctor
    HashTable(int cap) :
        size(0), capacity(cap), A(new HashTableEntry[cap])
    {
        ...
    }
    ...
    void rehash()
    {
        ...
        HashTableEntry* newMemoryRegion = new HashTableEntry[capacity];
        HashTableEntry* disposable = A;
        A = newMemoryRegion;
        ...
    }
    ...
};

关于C++嵌套类模板错误C2440 '=' : cannot convert from 'type' to 'same type' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51433831/

相关文章:

c++ - 如何使用 C++ 在 Solaris 中获取事件端口信息(重新创建 `netstat command`)?

c++ - 运算符 '.' 与 C++ 中的 '->'

c# - 在重新启动 dotnet 错误之前等待文件更改

c++ - initializer_list和move语义

php - 从 CodeIgniter HMVC 中的另一个模块加载 Controller

c++ - 模板参数列表短路?

c++ - 如何使用 Connector/C++ 在 MySQL 中连续更新一个值

c++ - Set表现异常:本地还是非本地?

visual-studio - 有没有办法使用通配符指定过滤器?

c# - A 类 DLL 不能转换为 B 类 DLL。 Type A originates.. from in the context LoadFrom