Jea*_*ier 26 c++ dictionary c++14 string-view
以下代码无法在最近的编译器上构建(g ++ - 5.3,clang ++ - 3.7).
#include <map>
#include <functional>
#include <experimental/string_view>
void f()
{
using namespace std;
using namespace std::experimental;
map<string, int> m;
string s = "foo";
string_view sv(s);
m.find(sv);
}
Run Code Online (Sandbox Code Playgroud)
clang返回的错误:
error: no matching member function for call to 'find'
m.find(sv);
~~^~~~
Run Code Online (Sandbox Code Playgroud)
但是不find应该能够使用类似的类型?Cppreference提到了以下重载:
template< class K > iterator find( const K& x );
发生同样的错误boost::string_ref.
Pio*_*cki 35
您需要明确指定透明比较器(如std::less<>):
std::map<std::string, int, std::less<>> m;
// ~~~~~~~~~~^
Run Code Online (Sandbox Code Playgroud)
std::map<K,V>将其比较器默认为std::less<K>(即,非透明的),并且因为([associative.reqmts]/p13):
成员函数模板
find,count,lower_bound,upper_bound,和equal_range不得除非参与重载分辨率合格-IDCompare::is_transparent是有效的,表示类型(14.8.2).
模板成员函数find不是一个可行的候选者.
关联容器的异构比较查找被添加到c ++ 14中.最初的提案有可能破坏现有代码.例如:
c.find(x);
Run Code Online (Sandbox Code Playgroud)
在语义上等同于:
key_type key = x;
c.find(key);
Run Code Online (Sandbox Code Playgroud)
特别是,之间的转换x和key_type发生一次,而实际调用之前.
异构查找替换赞成之间的比较,这种转换key和x.这可能会导致现有代码的性能下降(由于每次比较前的附加转换)或甚至中断编译(如果比较运算符是成员函数,则不会对左侧操作数应用转换):
#include <set>
#include <functional>
struct A
{
int i;
A(int i) : i(i) {}
};
bool operator<(const A& lhs, const A& rhs)
{
return lhs.i < rhs.i;
}
int main()
{
std::set<A, std::less<>> s{{1}, {2}, {3}, {4}};
s.find(5);
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,通过添加链接问题中描述的透明比较器的概念,使新行为成为选择.