【发布时间】:2012-03-27 08:53:24
【问题描述】:
我只是在启用 -std=c++11 的情况下使用 g++ 4.7(后来的快照之一)。我试图编译一些我现有的代码库,一个失败的案例让我有些困惑。
如果有人能解释发生了什么,我将不胜感激。
代码如下:
#include <utility>
#include <iostream>
#include <vector>
#include <string>
int main ( )
{
std::string s = "abc";
// 1 ok
std::pair < std::string, int > a = std::make_pair ( s, 7 );
// 2 error on the next line
std::pair < std::string, int > b = std::make_pair < std::string, int > ( s, 7 );
// 3 ok
std::pair < std::string, int > d = std::pair < std::string, int > ( s, 7 );
return 0;
}
我知道 make_pair 意味着用作 (1) 情况(如果我指定类型,那么我不妨使用 (3)),但我不明白为什么在这种情况下它失败了。
确切的错误是:
test.cpp: In function ‘int main()’:
test.cpp:11:83: error: no matching function for call to ‘make_pair(std::string&, int)’
test.cpp:11:83: note: candidate is:
In file included from /gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/utility:72:0,
from test.cpp:1:
/gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/bits/stl_pair.h:274:5:
note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_T1>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
/gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/bits/stl_pair.h:274:5:
note: template argument deduction/substitution failed:
test.cpp:11:83: note: cannot convert ‘s’ (type ‘std::string {aka std::basic_string<char>}’) to type ‘std::basic_string<char>&&’
同样,这里的问题只是“发生了什么事?”我知道我可以通过删除模板规范来解决问题,但我只是想知道这里到底出了什么问题。
- g++ 4.4 编译这段代码没有问题。
- 删除 -std=c++11 也可以正常编译代码。
【问题讨论】:
-
一个很好的问题。另一个 C++11 中微妙的突破性变化的例子,类似于 the breaking change in
std::vectorconstruction。至少这会产生编译器错误,而不是语义上的静默变化。 -
如果我有一个整数变量 i。我想与 i 和另一个对象配对。我应该怎么称呼makepair。 1) make_pair 2) int&& j = i; make_pair
?两者都不起作用。正确的做法是什么?
标签: c++ templates g++ c++11 rvalue-reference