我想了解为什么完全限定std::结果会导致下面的编译错误,使用std::transform.
#include <algorithm>
int main() {
std::string str;
std::transform(str.begin(), str.end(), str.begin(), std::tolower); // does not compile
std::transform(str.begin(), str.end(), str.begin(), ::tolower); // OK
}
Run Code Online (Sandbox Code Playgroud)
无法推导一元运算符的错误。
source>: In function 'int main()':
<source>:4:19: error: no matching function for call to 'transform(std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, std::__cxx11::basic_string<char>::iterator, <unresolved overloaded function type>)'
4 | std::transform(str.begin(), str.end(), str.begin(), std::tolower);
| ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/algorithm:62,
from <source>:1:
/opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/stl_algo.h:4285:5: note: candidate: 'template<class _IIter, class _OIter, class _UnaryOperation> constexpr _OIter std::transform(_IIter, _IIter, _OIter, _UnaryOperation)'
4285 | transform(_InputIterator __first, _InputIterator __last,
| ^~~~~~~~~
/opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/stl_algo.h:4285:5: note: template argument deduction/substitution failed:
<source>:4:19: note: couldn't deduce template parameter '_UnaryOperation'
4 | std::transform(str.begin(), str.end(), str.begin(), std::tolower);
| ~~~~~~~~~~~~~~^~~~~~~
Run Code Online (Sandbox Code Playgroud)
您需要指定您想要 std 命名空间中的哪一个函数:tolower
std::transform(str.begin(), str.end(), str.begin(), static_cast<int(*)(int)>(std::tolower));
Run Code Online (Sandbox Code Playgroud)
请注意,您还缺少string并cctype包含。