boost::my_map_list_of

boost::my_map_list_of

本文关键字:of list boost my map      更新时间:2023-10-16

我在理解boost::my_map_list_of函数时遇到了一些问题。特别是这部分:

operator Map const&() const { return data; }

有人能解释一下它是怎么工作的吗?以这种方式创建的映射是否在编译时初始化?

以下是整个提升:my_map_list_of()代码:

template<class K, class V>
struct map_list_of_type {
   typedef std::map<K, V> Map;
  Map data;
  map_list_of_type(K k, V v) { data[k] = v; }
  map_list_of_type& operator()(K k, V v) { data[k] = v; return *this; }
  operator Map const&() const { return data; }
};
template<class K, class V>
map_list_of_type<K, V> my_map_list_of(K k, V v) {
  return map_list_of_type<K, V>(k, v);
}
int main() {
  std::map<int, char> example = 
  my_map_list_of(1, 'a') (2, 'b') (3, 'c');
  cout << example << 'n';
}

main()中的代码正在调用函数my_map_list_of(),该函数返回一个map_list_of_type对象:

my_map_list_of(1, 'a')

然后,对返回的对象调用map_list_of_type::operator()。该函数返回相同的对象。

my_map_list_of(1, 'a') (2, 'b');
                       ^^^^^^^^

并且对新返回的对象再次调用CCD_ 6。

my_map_list_of(1, 'a') (2, 'b') (3, 'c');
                                ^^^^^^^^

然后,map_list_of_type::operator Map const&()被隐式调用,因为这个赋值需要它。对象map_list_of_type<int,char>被转换为std::map<int,char>

std::map<int, char> example = my_map_list_of(1, 'a') (2, 'b') (3, 'c');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
相关文章: