考虑以下 C++03 代码(我必须使代码与 C++11 之前的编译器兼容):
// This class belongs to a third-party SDK and cannot be touched
class A {
public:
explicit A();
explicit A(bool b);
private:
// Non-copyable
A(const A&);
const A& operator= (const A&);
}
boost::container::map<int, A> myMap;
在这里使用 Boost 映射,因为它甚至可以在 C++03 中进行放置。问题是,如果使用单参数构造函数,我可以完美地将构造嵌入到地图中,但我不知道如何默认构造对象,如下代码所示:
myMap.emplace(1, true); // Works
myMap.emplace(1); // Fails
第二次调用失败,因为它被视为对 emplace(std::pair...) 重载的调用,所以似乎没有办法“default-emplace”。
有什么方法可以实现我想要的吗?