0

I am trying to create a custom sort for a vector of class pointers by using a sort predicate:

struct sort_by_airtime                                                                                            
{                                                                                                                 
    inline bool operator() (const Network *n1, const Network *n2)                                                 
    {                                                                                                             
      return (n1->airtime() < n2->airtime());                                                                     
    }                                                                                                             
};      

For each network, we sort by a float returned by airtime().

Now, I try to use this as follows:

std::vector<Network *> Simulator::sort_networks(std::vector<Network *> netlist, bool sort_airtime) {

  std::vector<Network *> new_netlist = netlist;

  if(sort_airtime) {
    sort(new_netlist.begin(), new_netlist.end(), sort_by_airtime());
  }

}

However, I get a lot of errors like this:

In file included from Simulator.cpp:7:
Simulator.h: In member function ‘bool Simulator::sort_by_airtime::operator()(const Network*, const Network*)’:
Simulator.h:48: error: passing ‘const Network’ as ‘this’ argument of ‘virtual float Network::airtime()’ discards qualifiers
Simulator.h:48: error: passing ‘const Network’ as ‘this’ argument of ‘virtual float Network::airtime()’ discards qualifiers

Am I not specifying the argument passed to the predicate properly? airtime() is implemented by classes that inherit the Network class.

gnychis
  • 6,819
  • 16
  • 71
  • 107

3 Answers3

5

The compiler is warning you that Network::airtime() is ignoring the const qualifiers on n1 and n2.

The solution would be to create a "const-correct" version of Network::airtime() (assuming it actually doesn't modify anything).

See this answer for an example.

Community
  • 1
  • 1
jacobhaven
  • 383
  • 3
  • 9
3

Your member function should be declared as const member function as:

virtual float Network::airtime() const 
                                 ^^^^^ //this makes the function const

because the pointers which you're using in operator() are pointing to const objects of type Network.

Nawaz
  • 341,464
  • 111
  • 648
  • 831
1

Network::airtime() is not const, and so can't be called via the const Network* you have in sort_by_airtime.

If possible, the best solution is to make airtime() const; otherwise change the sort_by_airtime arguments to Network*.

Mike Seymour
  • 242,813
  • 27
  • 432
  • 630