std::map 放置不可移动不可复制不可默认构造的类型
std::map emplace non-movable non-copyable non-default-constructible type
我想要一个 class 的地图,它没有复制构造函数,没有移动构造函数,也没有默认构造函数(我无法控制这个 class)。
我试过将 std::map::emplace 与 std::piecewise_construct 和 std::forward_as_tuple 参数一起使用,但似乎编译器告诉我这是不可能的,因为它首先尝试默认构造.
// Example program
#include <iostream>
#include <string>
#include <map>
#include <utility>
#include <tuple>
class stone
{
public:
stone() = delete;
stone(stone& s) = delete;
stone(stone&& s) = delete;
stone(const std::string& s) : str(s)
{
}
std::string str;
};
int main()
{
std::map<int, stone> m;
m.emplace(std::piecewise_construct, std::forward_as_tuple(5), std::forward_as_tuple("asdf"));
std::cout << "map[5]: " << m[5].str << "\n";
}
在此处查看带有编译器错误的示例:http://cpp.sh/8bbwh
我怎样才能完成这项工作?我试过查看类似的问题,但它们似乎没有包含任何对我的特定情况有用的答案。
std::map emplace non-movable non-copyable non-default-constructible type
像这样:
m.emplace(5, "asdf");
不需要std::piecewise_construct也不需要std::forward_as_tuple。
至于查找值,您不能使用下标运算符,因为这要求类型是默认可构造的 - 如果查找前值不在映射中,将使用默认构造。
要查找非默认可构造类型,您必须改用 map::find 或 map::at。前者 returns 迭代器结束,后者如果映射值不存在则抛出异常。
emplace 操作没有问题,但是,问题出在 std::map::operator[]
上,因为它要求 value_type
是默认可构造的。但是,stone
有一个已删除的默认构造函数。
相反,您可以使用没有该要求的 std::map::at
:
std::cout << "map[5]: " << m.at(5).str << "\n";
这是 demo。
我想要一个 class 的地图,它没有复制构造函数,没有移动构造函数,也没有默认构造函数(我无法控制这个 class)。
我试过将 std::map::emplace 与 std::piecewise_construct 和 std::forward_as_tuple 参数一起使用,但似乎编译器告诉我这是不可能的,因为它首先尝试默认构造.
// Example program
#include <iostream>
#include <string>
#include <map>
#include <utility>
#include <tuple>
class stone
{
public:
stone() = delete;
stone(stone& s) = delete;
stone(stone&& s) = delete;
stone(const std::string& s) : str(s)
{
}
std::string str;
};
int main()
{
std::map<int, stone> m;
m.emplace(std::piecewise_construct, std::forward_as_tuple(5), std::forward_as_tuple("asdf"));
std::cout << "map[5]: " << m[5].str << "\n";
}
在此处查看带有编译器错误的示例:http://cpp.sh/8bbwh
我怎样才能完成这项工作?我试过查看类似的问题,但它们似乎没有包含任何对我的特定情况有用的答案。
std::map emplace non-movable non-copyable non-default-constructible type
像这样:
m.emplace(5, "asdf");
不需要std::piecewise_construct也不需要std::forward_as_tuple。
至于查找值,您不能使用下标运算符,因为这要求类型是默认可构造的 - 如果查找前值不在映射中,将使用默认构造。
要查找非默认可构造类型,您必须改用 map::find 或 map::at。前者 returns 迭代器结束,后者如果映射值不存在则抛出异常。
emplace 操作没有问题,但是,问题出在 std::map::operator[]
上,因为它要求 value_type
是默认可构造的。但是,stone
有一个已删除的默认构造函数。
相反,您可以使用没有该要求的 std::map::at
:
std::cout << "map[5]: " << m.at(5).str << "\n";
这是 demo。