Tuesday, October 3, 2017

C++14: Heterogeneous lookup in associative containers

C++14 added heterogeneous lookup in associative containers. It is enabled by specifying ‘less<>’ in the container template. Here is an example:

#include <iostream>
#include <functional>
#include <set>
using namespace std;

class MyClass0
{
  int mId;
 public:
  MyClass0(int id) : mId(id) {cout << "CTOR0 ";}
  bool operator< (const MyClass0 & rhs) const
  {
    return this->mId < rhs.mId;
  }
};

class MyClass1
{
  int mId;
 public:
  MyClass1(int id) : mId(id) {cout << "CTOR1 ";}
  bool operator< (const MyClass1 & rhs) const
  {
    return this->mId < rhs.mId;
  }
};

class MyClass2
{
  int mId;
 public:
  MyClass2(int id) : mId(id) {cout << "CTOR2 ";}
  bool operator< (const MyClass2 & rhs) const
  {
    return this->mId < rhs.mId;
  }
};

int main()
{
  set<MyClass0                 > mySet0;
  set<MyClass1, less<        > > mySet1; // Allows Heterogeneous Lookup.
  set<MyClass2, less<MyClass2> > mySet2;

  set<MyClass0                 >::iterator mySet0_iter;
  set<MyClass1, less<        > >::iterator mySet1_iter;
  set<MyClass2, less<MyClass2> >::iterator mySet2_iter;

  MyClass0 myObject0_1(1);
  mySet0.insert(myObject0_1);
  mySet0_iter=mySet0.find(myObject0_1);cout<<(mySet0_iter!=mySet0.end())<<" ";
  mySet0_iter=mySet0.find(MyClass0(1));cout<<(mySet0_iter!=mySet0.end())<<" ";
  mySet0_iter=mySet0.find(1          );cout<<(mySet0_iter!=mySet0.end())<<" ";
  cout << endl;

  MyClass1 myObject1_1(1);
  mySet1.insert(myObject1_1);
  mySet1_iter=mySet1.find(myObject1_1);cout<<(mySet1_iter!=mySet1.end())<<" ";
  mySet1_iter=mySet1.find(MyClass1(1));cout<<(mySet1_iter!=mySet1.end())<<" ";
  // The following does not compile in MSVS2014.
  //mySet1_iter=mySet1.find(1          );cout<<(mySet1_iter!=mySet1.end())<<" ";
  cout << endl;

  MyClass2 myObject2_1(1);
  mySet2.insert(myObject2_1);
  mySet2_iter=mySet2.find(myObject2_1);cout<<(mySet2_iter!=mySet2.end())<<" ";
  mySet2_iter=mySet2.find(MyClass2(1));cout<<(mySet2_iter!=mySet2.end())<<" ";
  mySet2_iter=mySet2.find(1          );cout<<(mySet2_iter!=mySet2.end())<<" ";

  cout << endl;
  return 0;
}
// Output(MSVS): CTOR0 1 CTOR0 1 CTOR0 1
//               CTOR1 1 CTOR1 1
//               CTOR2 1 CTOR2 1 CTOR2 1
//
// Output(g++):  CTOR0 1 CTOR0 1 CTOR0 1
//               CTOR1 1 CTOR1 1 CTOR1 1
//               CTOR2 1 CTOR2 1 CTOR2 1
Reference: https://en.wikipedia.org/wiki/C%2B%2B14#Heterogeneous_lookup_in_associative_containers

No comments:

Post a Comment