gpt4 book ai didi

c++ - 比较 unique_ptr 的映射

转载 作者:太空狗 更新时间:2023-10-29 20:56:14 25 4
gpt4 key购买 nike

是否有可能比较两个包含 std::unique_ptr 的映射?

在我的具体情况下,我想比较两个包含 std::unique_ptr 元组的映射(std::tuple 部分与问题无关,但是我认为在手动实现最基本的操作(如比较)时考虑使用异构类型引起的复杂性很重要。

class MyObject
{
public:
bool operator==(const MyObject& other) const
{
return member1 == other.member1;
}

bool operator!=(const MyObject& other) const;

private:
std::string member1 = "specific string";
};

TEST(General, CompareMapOfTuplesOfUniquePtrs)
{
using MyType = std::map<int32_t, std::tuple<int32_t, std::unique_ptr<MyObject>>>;

MyType map1;
MyType map2;

map1.insert({ 1, std::make_tuple(2, std::make_unique<MyObject>()) });
map2.insert({ 1, std::make_tuple(2, std::make_unique<MyObject>()) });

ASSERT_EQ(map1, map2);
}

显然,当我运行上面的测试(使用 Google Test)时,测试将失败,因为比较的是地址,而不是值(为此 operator==operator!= 被提供)。

Actual: { (1, (2, 4-byte object <B8-BF 86-01>)) }
Expected: map1
Which is: { (1, (2, 4-byte object <A0-BC 86-01>)) }
[FAILED]

我可以手动迭代每一对并取消引用每个对象,但我想知道是否有针对 unique_ptr 的更标准化的解决方案,因为它是一个基本构造。

最佳答案

我能想到的最标准的解决方案就是为该元组定义自己的相等运算符:

bool operator==( const std::tuple<int32_t, std::unique_ptr<MyObject>> & a,
const std::tuple<int32_t, std::unique_ptr<MyObject>> & b )
{
return std::get<0>(a) == std::get<0>(b) && *std::get<1>(a) == *std::get<1>(b);
}

这个例子对你来说可能已经足够了,除非你还想处理 nullptr。如果您对其他元组使用相同的模式,那么对其进行模板化可能是有意义的:

template < class A, class B >
bool operator==( const std::tuple<A, std::unique_ptr<B>> & a,
const std::tuple<A, std::unique_ptr<B>> & b )
{
return std::get<0>(a) == std::get<0>(b) && *std::get<1>(a) == *std::get<1>(b);
}

关于c++ - 比较 unique_ptr 的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34031967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com