I have a question about accessing methods of a type used in the instantiation of a template class in C++ and would greatly appreciate any help. I have researched this and nothing I can find on the internet helps with my specific problem.
Basically, I have a template class for a simple array/bag data structure.
Then, I have a template class for a dictionary, which uses the ABag class. (enough code for a min. reproducible example is below.)
There is also a KVpair class with methods related to key-value pairs (get the key, get the value, set them, etc.)
So, my question is this: When I instantiate the BDictionary class as an ABag of so many KVpairs (such as BDictionary<int, string> myDict(20);
, how can I access methods of the KVpair class for the nth element of myDict? I have a find function in BDictionary for which I need to know the key and value of any given element of myDict.
But I get the C2440 error as shown in the below code. How can I find the key and value, using the methods in KVpair class, for the nth element of myDict?
(Again, I've spent a good bit of time looking up this issue but I just can't find anything specific to my problem.)
Here is enough code for a minimal reproducible example:
template <typename E>
class ABag {
};
template <typename Key, typename E>
class KVpair {};
template <typename Key, typename E>
class BDictionary {
public:
bool find(const Key& k, E& rtnval) const {
for (size_t cur_pos = 0; cur_pos < 0; cur_pos++) {
KVpair<Key, E> temp = dictionary[cur_pos];
}
return false;
}
private:
ABag<KVpair<Key, E>> *dictionary;
};
int main() {
BDictionary<int, int> d;
int rv = 0;
d.find(0, rv);
}
Again, I need to access the keys and values of different entries in the find function. Please help!
I need to keep the pointer at ABag<KVpair<Key, E>>* dictionary. Removing the '*' causes some of the KVpair functions to throw an access violation error (the error described at Access Violation writing location 0xCDCDCDCD, but in a much different setting).
Solved using a combination of 3CxEZiVlQ and Useless's answers:
#include <cstdlib>
template <typename E>
class ABag {
int used;
E* data;
public:
E& operator[](size_t idx) { // from 3CxEZiVlQ
if (idx >= used)
{exit(-1);}
return data[idx];
}
};
template <typename Key, typename E>
class KVpair {};
template <typename Key, typename E>
class BDictionary {
public:
bool find(const Key& k, E& rtnval) const {
for (size_t cur_pos = 0; cur_pos < 0; cur_pos++) {
KVpair<Key, E> temp = (*dictionary)[cur_pos]; // from Useless
}
return false;
}
private:
ABag<KVpair<Key, E>> *dictionary;
};
int main() {
BDictionary<int, int> d;
int rv = 0;
d.find(0, rv);
}