Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.






(C++) SameXandY


SameXandY is a functor that checks for equality of an x and y value.







Technical facts


Application type(s)

Operating system(s) or programming environment(s)


Project type:

C++ standard:


Libraries used:






Qt project file: CppSameXandY.pro


CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -Wall -Wextra -Weffc++ -Werror
SOURCES += main.cpp








#include <cassert>
#include <functional>
#include <vector>
#include <algorithm>

struct Coordinat
  explicit Coordinat(const int x, const int y) : m_x(x), m_y(y) {}
  int x() const { return m_x; }
  int y() const { return m_y; }

  int m_x;
  int m_y;

//Temporarily suppress the -Weffc++ compiler option
//  caused by inheriting from std::unary_function.
//See http://richelbilderbeek.nl/CppWeffcpp.htm
#pragma GCC diagnostic ignored "-Weffc++"

//From http://www.richelbilderbeek.nl/CppSameXandY.htm
template <class T>
struct SameXandY : public std::unary_function<T,bool>
  explicit SameXandY(const T& coordinat) : m_coordinat(coordinat) {}
  bool operator()(const T& coordinat) const
    return coordinat.x() == m_coordinat.x() && coordinat.y() == m_coordinat.y();

  const T m_coordinat;

//Restore the -Weffc++ compiler option,
#pragma GCC diagnostic pop

int main()
  std::vector<Coordinat> v;
  for (int i=0; i!=10; ++i) v.push_back(Coordinat(i,i));
  assert( std::find_if(v.begin(), v.end(), SameXandY<Coordinat>(Coordinat(3,5))) == v.end());
  assert( std::find_if(v.begin(), v.end(), SameXandY<Coordinat>(Coordinat(5,5))) != v.end());






Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.


Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml