Witam. Czy możliwe jest przesłanie operatora jako argumentu funkcji ?
coś na zasadzie:
void Wyswietl(const Macierz & m1, const Macierz & m2, operator op)
{
cout << m1 << endl;
cout << m2 << endl;
cout << m2 op m1 << endl;
}
Witam. Czy możliwe jest przesłanie operatora jako argumentu funkcji ?
coś na zasadzie:
void Wyswietl(const Macierz & m1, const Macierz & m2, operator op)
{
cout << m1 << endl;
cout << m2 << endl;
cout << m2 op m1 << endl;
}
C++11:
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); });
Korzystając ze wskaźnika do funkcji:
#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;
}
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:
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;
}
@EvilOne przekombinowałeś. Definiowanie takich operatorów nie jest najlepszym pomysłem.
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))