Przesłanie operatora jako argumentu

Przesłanie operatora jako argumentu
darthachill
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 94
0

Witam. Czy możliwe jest przesłanie operatora jako argumentu funkcji ?

coś na zasadzie:

Kopiuj
 
void Wyswietl(const Macierz & m1, const Macierz & m2, operator op)
{
    cout << m1 << endl;
    cout << m2 << endl;
    cout << m2 op m1 << endl;
}
MarekR22
  • Rejestracja: dni
  • Ostatnio: dni
5

C++11:

Kopiuj
typedef std::function<bool(const Macierz & m1, const Macierz & m2)> MatrixComparator;
void Wyswietl(const Macierz & m1, const Macierz & m2, MatrixComparator comparator) {
    cout << m1 << endl;
    cout << m2 << endl;
    cout << comparator(m2, m1) << endl;
}

Wyswietl(m1, m2, [](const Macierz & m1, const Macierz & m2) { return m1(1,2)<m2(1,2); });
MC
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 5
2

Korzystając ze wskaźnika do funkcji:

Kopiuj
#include <iostream>
using namespace std;

class Macierz{
};

Macierz operator+(const Macierz &a, const Macierz &b)
{
	cout << "operator + called" << endl;
	return Macierz();
}

ostream& operator<< (ostream &out, const Macierz &a)
{
	out << "(Macierz)";
    return out;
}

void Wyswietl(const Macierz & m1, const Macierz & m2, Macierz (*op)(const Macierz &, const Macierz &))
{
    cout << m1 << endl;
    cout << m2 << endl;
    cout << op(m1, m2) << endl;
}

int main() {
	Macierz a, b;
	Wyswietl(a, b, operator+);
	
	return 0;
} 
EvilOne
  • Rejestracja: dni
  • Ostatnio: dni
  • Postów: 78
0

Jeśli jednak z jakichś powodów nie chciałbyś korzystać ze standardu C++11 to możesz skorzystać z gotowych funktorów ze standardowej biblioteki functional i napisać to tak:

Kopiuj
class Matrix
{
public:
	bool operator <(const Matrix&) const
	{
		return true;
	}

	bool operator ==(const Matrix&) const
	{
		return true;
	}

	bool operator !=(const Matrix&) const
	{
		return true;
	}

	bool operator >(const Matrix&) const
	{
		return true;
	}
};

template <typename T>
void Wyswietl(const Matrix& m1, const Matrix& m2, const T& comparison)
{
    std::cout << comparison(m1, m2) << std::endl;
}

int main()
{
	Matrix a, b;

	Wyswietl(a, b, std::less<Matrix>());
	
	Wyswietl(a, b, std::equal_to<Matrix>());

	Wyswietl(a, b, std::not_equal_to<Matrix>());

	Wyswietl(a, b, std::greater<Matrix>());

	return 0;
}
MarekR22
  • Rejestracja: dni
  • Ostatnio: dni
1

@EvilOne przekombinowałeś. Definiowanie takich operatorów nie jest najlepszym pomysłem.

Kopiuj
typedef binary_function<Matrix,Matrix,bool> MatrixComparator;
void Wyswietl(const Macierz & m1, const Macierz & m2, MatrixComparator comparator)
{
    std::cout << comparator(m1, m2) << std::endl;
}

Wyswietl(m1, m2, std::mem_fun_ref<bool>(&Macierz::jakiesPorownanie))

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.