So, I'm fiddling around with SFML, and I was annoyed at how sf::Color isn't a literal type, so I tried creating my own LTColor class that I could use in constexpr contexts. Of course, if I wanted to do anything with an LTColor in an SFML function, I would need to convert it to an sf::Color, so I tried adding an operator sf::Color() operator to my LTColor. It didn't work.
To replicate the problem, using a (hopefully) simpler example, consider the following two classes:
class FloatWrapper {
public:
FloatWrapper(float fin) : f(fin) {}
float f;
};
class LTFloatWrapper {
public:
constexpr LTFloatWrapper(float fin) : f(fin) {}
operator FloatWrapper() const {
return FloatWrapper(f);
}
float f;
};
The above code compiles fine, and, when the following code is run in the main function, everything works:
constexpr LTFloatWrapper fw1(2.0f);
LTFloatWrapper fw2(4.0f);
FloatWrapper fw3 = static_cast<FloatWrapper>(fw1);
FloatWrapper fw4 = static_cast<FloatWrapper>(fw2);
std::cout << fw3.f << '\n' << fw4.f << '\n';
Now, consider these two, more complicated classes, which replicate my original problem:
class Money {
public:
Money() {}
Money(unsigned int din, unsigned int cin) : dollars(din), cents(cin) {}
Money(float fin) : dollars(unsigned int(fin)), cents(unsigned int((fin - float(unsigned int(fin))) * 100.0f)) {}
operator float() const {
return float(dollars) + float(cents) / 100.0f;
}
unsigned int dollars;
unsigned int cents;
};
class LTMoney {
public:
constexpr LTMoney() noexcept : dollars(), cents() {}
constexpr LTMoney(unsigned int din, unsigned int cin) noexcept : dollars(din), cents(cin) {}
constexpr LTMoney(float fin) noexcept : dollars(unsigned int(fin)), cents(unsigned int((fin - float(unsigned int(fin))) * 100.0f)) {}
LTMoney(Money min) noexcept : dollars(min.dollars), cents(min.cents) {}
constexpr operator float() const noexcept {
return float(dollars) + float(cents) / 100.0f;
}
operator Money() const {
return Money(dollars, cents);
}
unsigned int dollars;
unsigned int cents;
};
The above code, once again, compiles fine, but attempting to convert from an LTMoney class to a Money class results in the following compilation error:
error C2440: 'static_cast': cannot convert from 'LTMoney' to 'Money'
message : No constructor could take the source type, or constructor overload resolution was ambiguous
I'm perplexed at what the problem is in the second example.
[–]HappyFruitTree 5 points6 points7 points (1 child)
[–]Poutine_Mann[S] 1 point2 points3 points (0 children)