c++ 错误C2660:“标准::对〈a,B>::对”:函数不接受2个参数

8aqjt8rx  于 2022-11-27  发布在  其他
关注(0)|答案(1)|浏览(141)

我正在尝试创建一个结构并插入一个Map,如下所示:

struct Queue_ctx {
      std::mutex qu_mutex;
      std::condition_variable qu_cv;
      std::queue<std::vector<std::byte>> qu;
    };

    std::map<std::string, Queue_ctx> incoming_q_map;
    Queue_ctx qctx;
    std::vector<std::byte> vect(100);
    qctx.qu.push(vect);
    incoming_q_map.emplace("actor", qctx);

但我得到以下错误:

error C2660: 'std::pair<const std::string,main::Queue_ctx>::pair': function does not take 2 arguments
 
message : see declaration of 'std::pair<const std::string,main::Queue_ctx>::pair'

message : see reference to function template instantiation 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,const char(&)[6],main::Queue_ctx&>(_Alloc &,_Objty *const ,const char (&)[6],main::Queue_ctx &)' being compiled
        with
        [
            _Alloc=std::allocator<std::_Tree_node<std::pair<const std::string,main::Queue_ctx>,std::_Default_allocator_traits<std::allocator<std::pair<const std::string,main::Queue_ctx>>>::void_pointer>>,
            _Ty=std::pair<const std::string,main::Queue_ctx>,
            _Objty=std::pair<const std::string,main::Queue_ctx>
        ]

AFAIU,emplace构造了元素inplace。如果这是真的,那么为什么编译器试图创建pair来进行emplace?我发现编译器合成的pair的语法很奇怪,这就是它抱怨的原因。但是为什么会发生这种情况,我该怎么做来解决这个问题?
我试图显式传递make_pair(),但没有任何帮助。
如果我注解了qu_mutexqu_cv,那么我就可以执行emplace。error和这两个成员有什么关系?不是默认consutructor初始化struct的成员的情况吗?我知道copy/assignment/move构造函数被编译器删除了。

kzmpq1sx

kzmpq1sx1#

无论如何,要解决这个问题,你需要定制复制构造函数和赋值运算符。另外,互斥体建议在所有场景中对qu进行一些同步,所以所有字段都应该是私有的(所以struct应该改为class)。

class Queue_ctx {
    mutable std::mutex qu_mutex;
    std::condition_variable qu_cv;
    std::queue<std::vector<std::byte>> qu;

public:
    Queue_ctx() = default;
    Queue_ctx(const Queue_ctx& other)
        : Queue_ctx(other, std::scoped_lock{ other.qu_mutex })
    {
    }

    Queue_ctx(const Queue_ctx& other, const std::scoped_lock<std::mutex>&)
        : qu { other.qu }
    {
    }

    Queue_ctx(Queue_ctx&& other)
    : Queue_ctx(std::move(other), std::scoped_lock{ other.qu_mutex })
    {
    }

    Queue_ctx(Queue_ctx&& other, const std::scoped_lock<std::mutex>&)
        : qu { std::move(other.qu) }
    {
    }

    Queue_ctx& operator=(const Queue_ctx& other)
    {
        std::scoped_lock lock{ qu_mutex, other.qu_mutex };
        qu = other.qu;
        return *this;
    }

    Queue_ctx& operator=(Queue_ctx&& other)
    {
        std::scoped_lock lock{ qu_mutex, other.qu_mutex };
        qu = std::move(other.qu);
        return *this;
    }

    void push(const std::vector<std::byte>& v)
    {
        std::unique_lock lock{ qu_mutex };
        qu.push(v);
    }

    void push(std::vector<std::byte>&& v)
    {
        std::unique_lock lock{ qu_mutex };
        qu.push(std::move(v));
    }
};

https://godbolt.org/z/xn6orTedz
它可以编译,但是需要更多的测试。注意,使用qu_cv缺少一些功能。

相关问题