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

标签 c++ boost constructor stl stdmap

我正在尝试构造一个对象,该对象采用 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/

相关文章:

C++ 初始化类成员构造函数

Swift - 根据函数参数分配局部变量

c++ - 从字符串中复制选定的字符

C++ 将指针从一个派生类转换为另一个派生类

c++ - boost::serialization 反序列化 xml_archive 异常

c++ - TagLib: 无法打开文件

c++ - 为什么 Visual Studio 无法编译我的 QT 项目,因为它找不到库?

c++ - 单张图像的相机校准?它似乎有效,但我错过了什么吗?

c++ - 对 boost::filesystem::detail::copy_file 的 undefined reference

c++ - 使用构造函数参数实例化类对象和不带参数 C++ 的 * 运算符之间的区别