gpt4 book ai didi

c++ - 为什么我可以将 boost map_list_of 传递给接受映射而不是构造函数的函数?

转载 作者:可可西里 更新时间:2023-11-01 17:50:24 24 4
gpt4 key购买 nike

我正在尝试构造一个对象,该对象采用 std::map 作为参数,方法是使用 boost map_list_of 将 map 内容传递给它。

这会产生编译错误,但是,当我尝试对采用 std::map 的常规函数​​执行相同操作时,它编译正常!

#include <map>
#include <boost/assign.hpp>

struct Blah
{
Blah(std::map<int, int> data) {}
};

void makeBlah(std::map<int, int> data) {}

int main()
{
Blah b(boost::assign::map_list_of(1, 2)(3, 4)); // Doesn't compile.

makeBlah(boost::assign::map_list_of(1, 2)(3, 4)); // Compiles fine!
}

我得到的编译错误是:

error: call of overloaded ‘Blah(boost::assign_detail::generic_list<std::pair<int, int> >&)’ is ambiguous
note: candidates are: Blah::Blah(std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >)
note: Blah::Blah(const Blah&)

有什么歧义,为什么它不影响常规函数 makeBlah,据我所知,它与 Blah 构造函数具有相同的签名?

有没有更好的方法来实现这个,除了制作一个 makeBlah 函数来构造一个 Blah 的对象,看起来我必须这样做?

(顺便说一句,我在使用 map_list_of 的单元测试中执行此操作以使测试输入数据创建更具可读性)

最佳答案

map_list_of不会创建容器,但会创建一个

anonymous list which can be converted to any standard container

转换是通过模板用户定义的转换运算符完成的:

   template< class Container >
operator Container() const;

所以在构造函数的上下文中,它无法推断是否转换为 map<int, int>Blah .为避免这种情况,例如,您可以添加一个虚拟构造函数参数:

class Blah
{
public:
Blah(std::map<int, int> data, int)
{
}

};

void makeBlah(std::map<int, int> data)
{
}

void myTest()
{
Blah b(boost::assign::map_list_of(1, 2)(3, 4), 0);

makeBlah(boost::assign::map_list_of(1, 2)(3, 4));
}

随着 makeBlah你没有这样的歧义。

或者,您可以将列表类型作为构造函数参数,然后在Blah 中使用它。 :

class Blah
{
public:
Blah(decltype(boost::assign::map_list_of(0, 0)) data)
: m(data.to_container(m))
{
}

std::map<int, int> m;
};

关于c++ - 为什么我可以将 boost map_list_of 传递给接受映射而不是构造函数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32893027/

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