boost::my_map_list_of
boost::my_map_list_of
我在理解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');
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- 如何将 std::list of 派生类而不是 std::list of parent class 传递给函数
- 将 std::list of structs 转换为 Python 列表
- 矩阵类:"No instance of overloaded function push_back matches the argument list"
- 如何修复'Size of list( a class) is unknown or zero error'和"声明语法错误"?
- 为什么我会收到错误"parameter pack 'F' must be at the end of the template parameter list"
- 在递归函数中创建 std::list of value 而不是 std::list of 指针
- 将<Point2f> openCV 的向量转换为 Collections::Generic::List<Windows::P oint> of C#
- std::map with iterators to std::list from iterators of std::
- "ISO C++ forbids declaration of 'list' with no type"错误
- "more than one instance of overloaded function " 标准::p ow " matches the argument list"
- MSVC:"use of class template requires template argument list" STL 容器内
- C++:"invalid initialization of non-const reference of type ‘List&’ from a temporary of type ‘List*’"
- "a list of vectors of ints" - 这可能吗?
- "use of class template requires template argument list"错误,即使使用了模板的模板,因此模板类是预期的
- "use of class template requires template argument list"是什么意思?
- 零MQ的"expected ';' at the end of declaration list"错误