Home > other >  Cannot convert from const_Ty2* to ValueType*
Cannot convert from const_Ty2* to ValueType*

Time:03-09

template <typename ValueType> ValueType* RadixTree<ValueType>::search(std::string key) const {
    typename std::map<std::string, ValueType>::const_iterator it = radixTree.find(key);
    if (it == radixTree.end())
        return nullptr;
    return &(it->second);
}

Hello! above is my code which is a placeholder for my radixTree implementation. I don't understand why I need the typename before the std::map on the second line, and why &(it->second) would end up returning a const_Ty2*. I thought that in this case, const_Ty2 and ValueType were equivalent. The variable radixTree is currently a Map, and although I want to replace this with my radixTree implementation, I also want to understand the problem I'm getting right now. Any help would be greatly appreciated. Thank you!

Follow up: I'm also getting an issue w/ this method

template <typename ValueType> void RadixTree<ValueType>::insert(std::string key, const ValueType& value) {
    radixTree.insert(key, value);
}

and radixTree is declared as std::map<std::string,ValueType> radixTree; This method gives me a really long error that I can't quite understand.

std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>,std::pair<const std::string,ValueType> &&)': cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>

Can someone help me w/ this too? Thank you again!

CodePudding user response:

Your function is const and you're correctly using a const_iterator. This means that it->second is also const. When you do &it->second that becomes a const pointer which cannot be implicitly converted to a non-const pointer (such a conversion discards the const qualifier).

It's unclear why you want a non-const pointer to an internal value. I have to presume it's an error. You should change the return type to const ValueType*.

Regarding the edit you just made to your question:

radixTree.insert(key, value);

The message is telling you that the function arguments are wrong. Check the documentation for the insert function. You'll find that it requires a value_type which is a std::pair<const Key, T>. The useful part of the error is here:

cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>

There it is trying to match a call that has two arguments, which the overload resolution is trying to resolve it to insert(const_iterator hint, const value_type &value). That should tell you something is wrong.

Try this:

radixTree.insert(std::make_pair(key, value));
  • Related