无法在std::map中使用std::shared_ptr作为值类型?

3
我有以下这个类,我想将它作为一个shared_ptr添加到一个map中。
struct texture_t
{
hash32_t hash;
uint32_t width;
uint32_t height;
uint32_t handle;
};

我尝试使用make_pair,然后将其添加到map中...

auto texture = std::make_shared<texture_t>(new texture_t());
std::make_pair<hash32_t, std::shared_ptr<texture_t>>(hash32_t(image->name), texture);

在使用make_pair时,我收到以下编译错误:

error C2664: 'std::make_pair' : cannot convert parameter 2 from 'std::shared_ptr<_Ty>' to 'std::shared_ptr<_Ty> &&'

我感觉自己错过了一些明显的东西,你有什么线索吗?

1个回答

5

std::make_pair不应该使用显式模板参数。只需要省略它们:

auto my_pair = std::make_pair(hash32_t(image->name), texture);

注意:调用 make_shared 的方式也是错误的。参数应该传递给 texture_t 的构造函数,因此在这种情况下只需要:

auto texture = std::make_shared<texture_t>();

调用 make_shared 也是错误的。这个问题已经在 OP 的后续问题 中得到了修复,但为了完整起见,在这里可能值得一提。 - juanchopanza
3
你可以使用.emplace将这对键值对插入到map中,无需手动构建它。具体可写为:map.emplace(hash32_t(image->name), std::make_shared<texture_t>()) - kennytm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接