下面的法典没有把我编成一个想法,说明为什么:
#include <memory>
#include <iostream>
#include <map>
template <typename MapT>
inline typename MapT::mapped_type * find_element(MapT &m, const typename MapT::key_type &key)
{
auto it = m.find(key);
return it != m.end() ? &it->second : NULL;
}
int main() {
std::map<std::string, double> map0;
const std::map<std::string, double> map1 = map0;
auto d1 = find_element(map1, "test");
std::cout << d1 << "
";
}
我收到了:
const.cc: In instantiation of ‘typename MapT::mapped_type* find_element(MapT&, const typename MapT::key_type&) [with MapT = const std::map<std::__cxx11::basic_string<char>, double>; typename MapT::mapped_type = double; typename MapT::key_type = std::__cxx11::basic_string<char>]’:
const.cc:15:38: required from here
const.cc:9:24: error: invalid conversion from ‘const double*’ to ‘std::map<std::__cxx11::basic_string<char>, double>::mapped_type*’ {aka ‘double*’} [-fpermissive]
9 | return it != m.end() ? &it->second : NULL;
| ^
| |
| const double*