Introduction
In C++ class we are learning to use functors, lambdas and function pointers. Now we got a different behavior on the teachers computer and that of many students. The problem appears when a custom Functor (FractionComparator) is used in combination with the std::function Function wrapper and it appears on different OS and IDEs.
We tested this on Windows Machines with VisualStudio and Eclipse as well on OSX Machines with XCode and CLion. The <funtional>
header is included.
Problem
function<int(Fraction, Fraction)> comparator = FractionComparator();
This is the code the teacher gave us and which works on his machine. But on many of the students computer, a compiling error similar to the following one appears. This example is from XCode.
No viable conversion from 'FractionComparator' to 'function'
What we already found out, is that if we implement a move constructor in the Fraction class, the assignment works as expected. Now we are stuck on the search for an explanation for this differing behavior and hope to find enlightenment with help of the stackoverflow community.
Fraction class
class Fraction{
public:
Fraction();
Fraction(int z, int n);
Fraction(Fraction&);
// Fraction(Fraction&&);
int getNumerator() const;
int getDenominator() const;
void setNumerator(int);
void setDenominator(int);
Fraction& operator=(const Fraction&);
bool operator<(const Fraction&);
bool operator>(const Fraction&);
private:
int m_numerator;
int m_denominator;
};
Fraction comparator
class FractionComparator {
public:
int operator()(Fraction a, Fraction b) {
double z1 = a.getNumerator();
double n1 = a.getDenominator();
double z2 = b.getNumerator();
double n2 = b.getDenominator();
if (z1/n1 < z2/n2) return -1;
else if (z1/n1 > z2/n2) return +1;
return 0;
}
};
Main
int main(int argc, char** argv){
function<int(Fraction, Fraction)> comparator = FractionComparator();
}
Aucun commentaire:
Enregistrer un commentaire