关于VS2012使用make_pair编译提示“error C2664: “std::make_pair”: 不能将参数 1 从“int”转换为“int &&””

本文介绍了一个关于C++中使用std::make_pair时出现类型转换错误的问题,并提供了两种解决方案:通过预处理器宏FIX1直接构造临时对象或者通过FIX2使用标准库函数make_pair。这两种方式都能创建一个pair对象并进行类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



参照微软官方回复:

#include <iostream>
#include <ostream>
#include <string>
#include <utility>
using namespace std;

int main() {
    string ht = "hello";
    pair<double, string> ps;

#if defined(FIX1)
    ps = pair<int, string>(1, ht);
#elif defined(FIX2)
    ps = make_pair(1, ht);
#else
    ps = make_pair<int, string>(1, ht);
#endif

    cout << ps.first << " " << ps.second << endl;
}

C:\Temp>cl /EHsc /nologo /W4 kitty.cpp && kitty
kitty.cpp
kitty.cpp(16) : error C2664: 'std::make_pair' : cannot convert parameter 2 from 'std::string' to 'std::string &&'
        You cannot bind an lvalue to an rvalue reference

C:\Temp>cl /EHsc /nologo /W4 kitty.cpp /DFIX1 && kitty
kitty.cpp
1 hello

C:\Temp>cl /EHsc /nologo /W4 kitty.cpp /DFIX2 && kitty
kitty.cpp
1 hello

Both FIX1 and FIX2 construct a temporary pair<int, string>, which is then converted during assignment to pair<double, string>.

I personally recommend FIX2.

https://connect.microsoft.com/VisualStudio/feedback/details/691756/std-make-pair-error-in-vc11

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值