以下代码无法编译,我不知道为什么:
#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 << "\n";
}
我得到:
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*
问题是
MapT
被推导为 const std::map<std::string, double>
,因为您传递的是 const 映射。这反过来意味着 it
被推导为(从初始化器)为 std::map<const std::string, double>::const_iterator
。因此, it->second
的类型将为 const double
且 &it->second
为 const double*
。
由于返回类型是
double*
并且我们不允许从 double*
初始化 const double*
,因此您会收到上述错误。