我需要有人一行一行地向我解释这段代码.我特意不理解这一行:
operator std::map<T, U>()
Run Code Online (Sandbox Code Playgroud)
非常感谢你.
template <typename T, typename U>
class create_map
{
std::map<T, U> m_map;
public:
create_map(const T& key, const U& val)
{
m_map[key] = val;
}
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return *this;
}
operator std::map<T, U>()
{
return m_map;
}
};
Run Code Online (Sandbox Code Playgroud)
operator std::map<T, U>()
{
return m_map;
}
Run Code Online (Sandbox Code Playgroud)
这是用户定义的转换功能.
这意味着,你可以这样写:
//obj is an object of type create_map
create_map<int,std::string> obj(1,"Nawaz");
//obj implicitly converts into std::map type!
std::map<int,std::string> map_inst=obj;
Run Code Online (Sandbox Code Playgroud)
请参阅此主题以了解有关用户定义的转换函数的更多信息:
您也可以看到这一点:隐式转换序列(仅限C++)
create_map<T, U>& operator()(const T& key, const U& val)
{
m_map[key] = val;
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这实际上会使operator()内部插入或更新(key,val)对重载到m_map; 只看函数定义它的作用.
所以使用这个函数你可以写这样的代码,
obj(2,"Sarfaraz"); //this inserts the pair into the underlying m_map;
Run Code Online (Sandbox Code Playgroud)
我还建议你多探索std::map一下,尤其是重载operator[]的std::map.
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |