Например:
operator bool() const
{
return col != 0;
}
col
является int. Как operator bool() const
работает?
Например:
operator bool() const
{
return col != 0;
}
col
является int. Как operator bool() const
работает?
Функции-члены формы
operator TypeName()
операторы преобразования. Они позволяют использовать объекты типа класса, как если бы они были типа, TypeName
и когда они есть, они преобразуются для TypeName
использования функции преобразования.
В этом конкретном случае operator bool()
позволяет использовать объект типа класса, как если бы он был bool
. Например, если у вас есть объект типа класса с именем obj
, вы можете использовать его как
if (obj)
Это вызовет operator bool()
, вернет результат и будет использовать результат как условие для if
.
Следует отметить, что operator bool()
это очень плохая идея, и вам никогда не следует ее использовать. Подробное объяснение того, почему это плохо, и решение проблемы см. В «Идиоме Safe Bool».
(В C ++ 0x, предстоящей версии стандарта C ++, добавлена поддержка операторов явного преобразования. Это позволит вам написать безопасный, explicit operator bool()
который работает правильно, без необходимости прыгать через обручи реализации Safe Bool Idiom.)
bool
), нет, вы не можете присвоить ему значение. Если бы это было изменяемое lvalue (напримерbool&
), вы могли бы присвоить ему. Что касается правильности, я утверждаю, чтоoperator bool()
всегда неверно, потому что оно позволяет использовать объект типа класса в огромном количестве ситуаций, когда вы никогда не хотите, чтобы он использовался. Safe Bool - намного лучшая альтернатива.explicit operator bool()
. Я правильно понял?operator bool() const { return col != 0; }
Определяет, как класс может быть преобразован в логическое значение,
const
после()
используется, чтобы указать, что этот метод не мутирует (изменить члены этого класса).Обычно вы используете следующие операторы:
airplaysdk sdkInstance; if (sdkInstance) { std::cout << "Instance is active" << std::endl; } else { std::cout << "Instance is in-active error!" << std::endl; }
источник
Я хотел бы привести больше кодов, чтобы было понятно.
struct A { operator bool() const { return true; } }; struct B { explicit operator bool() const { return true; } }; int main() { A a1; if (a1) cout << "true" << endl; // OK: A::operator bool() bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization B b1; if (b1) cout << "true" << endl; // OK: B::operator bool() // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool() bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization }
источник
Это определяемая пользователем
implicit
функция преобразования для преобразования вашего класса вtrue
илиfalse
.//usage bool value = yourclassinstance; //yourclassinstance is converted into bool!
источник
Это неявное преобразование в
bool
. Т.е. везде, где разрешены неявные преобразования, ваш класс можно преобразовать вbool
, вызвав этот метод.источник
Как уже говорили другие, это для преобразования типа, в данном случае в
bool
. Например:class A { bool isItSafe; public: operator bool() const { return isItSafe; } ... };
Теперь я могу использовать объект этого класса, как если бы он был логическим:
A a; ... if (a) { .... }
источник
При написании собственного unique_ptr я обнаружил этот случай. Учитывая
std::unique_ptr
«Soperator==
:template<class T1, class D1, class T2, class D2> bool operator==(const unique_ptr<T1, D1>& x, const unique_ptr<T2, D2>& y); template <class T, class D> bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept; template <class T, class D> bool operator==(nullptr_t, const unique_ptr<T, D>& x) noexcept;
И этот тестовый пример из libstdcxx :
std::unique_ptr<int> ptr; if (ptr == 0) { } if (0 == ptr) { } if (ptr != 0) { } if (0 != ptr) { }
Обратите внимание, потому что здесь
ptr
естьexplicit operator bool() const noexcept;
, поэтомуoperator overload resolution
отлично работает, например,ptr == 0
выбираетtemplate <class T, class D> bool operator==(const unique_ptr<T, D>& x, nullptr_t) noexcept;`.
Если здесь нет
explicit
ключевого слова,ptr
inptr == 0
будет преобразовано вbool
, затемbool
будет преобразовано вint
, потому чтоbool operator==(int, int)
оно встроено и0
естьint
. Нас ждет неоднозначная ошибка разрешения перегрузки.Вот минимальный, полный и поддающийся проверке пример :
#include <cstddef> struct A { constexpr A(std::nullptr_t) {} operator bool() { return true; } }; constexpr bool operator ==(A, A) noexcept { return true; } constexpr bool operator ==(A, std::nullptr_t) noexcept { return true; } constexpr bool operator ==(std::nullptr_t, A) noexcept { return true; } int main() { A a1(nullptr); A a2(0); a1 == 0; }
gcc :
prog.cc: In function 'int main()': prog.cc:30:8: error: ambiguous overload for 'operator==' (operand types are 'A' and 'int') 30 | a1 == 0; | ~~ ^~ ~ | | | | A int prog.cc:30:8: note: candidate: 'operator==(int, int)' <built-in> 30 | a1 == 0; | ~~~^~~~ prog.cc:11:16: note: candidate: 'constexpr bool operator==(A, A)' 11 | constexpr bool operator ==(A, A) noexcept | ^~~~~~~~ prog.cc:16:16: note: candidate: 'constexpr bool operator==(A, std::nullptr_t)' 16 | constexpr bool operator ==(A, std::nullptr_t) noexcept | ^~~~~~~~
лязг :
prog.cc:30:8: error: use of overloaded operator '==' is ambiguous (with operand types 'A' and 'int') a1 == 0; ~~ ^ ~ prog.cc:16:16: note: candidate function constexpr bool operator ==(A, std::nullptr_t) noexcept ^ prog.cc:11:16: note: candidate function constexpr bool operator ==(A, A) noexcept ^ prog.cc:30:8: note: built-in candidate operator==(int, int) a1 == 0; ^ prog.cc:30:8: note: built-in candidate operator==(float, int) prog.cc:30:8: note: built-in candidate operator==(double, int) prog.cc:30:8: note: built-in candidate operator==(long double, int) prog.cc:30:8: note: built-in candidate operator==(__float128, int) prog.cc:30:8: note: built-in candidate operator==(int, float) prog.cc:30:8: note: built-in candidate operator==(int, double) prog.cc:30:8: note: built-in candidate operator==(int, long double) prog.cc:30:8: note: built-in candidate operator==(int, __float128) prog.cc:30:8: note: built-in candidate operator==(int, long) prog.cc:30:8: note: built-in candidate operator==(int, long long) prog.cc:30:8: note: built-in candidate operator==(int, __int128) prog.cc:30:8: note: built-in candidate operator==(int, unsigned int) prog.cc:30:8: note: built-in candidate operator==(int, unsigned long) prog.cc:30:8: note: built-in candidate operator==(int, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(int, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(long, int) prog.cc:30:8: note: built-in candidate operator==(long long, int) prog.cc:30:8: note: built-in candidate operator==(__int128, int) prog.cc:30:8: note: built-in candidate operator==(unsigned int, int) prog.cc:30:8: note: built-in candidate operator==(unsigned long, int) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, int) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, int) prog.cc:30:8: note: built-in candidate operator==(float, float) prog.cc:30:8: note: built-in candidate operator==(float, double) prog.cc:30:8: note: built-in candidate operator==(float, long double) prog.cc:30:8: note: built-in candidate operator==(float, __float128) prog.cc:30:8: note: built-in candidate operator==(float, long) prog.cc:30:8: note: built-in candidate operator==(float, long long) prog.cc:30:8: note: built-in candidate operator==(float, __int128) prog.cc:30:8: note: built-in candidate operator==(float, unsigned int) prog.cc:30:8: note: built-in candidate operator==(float, unsigned long) prog.cc:30:8: note: built-in candidate operator==(float, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(float, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(double, float) prog.cc:30:8: note: built-in candidate operator==(double, double) prog.cc:30:8: note: built-in candidate operator==(double, long double) prog.cc:30:8: note: built-in candidate operator==(double, __float128) prog.cc:30:8: note: built-in candidate operator==(double, long) prog.cc:30:8: note: built-in candidate operator==(double, long long) prog.cc:30:8: note: built-in candidate operator==(double, __int128) prog.cc:30:8: note: built-in candidate operator==(double, unsigned int) prog.cc:30:8: note: built-in candidate operator==(double, unsigned long) prog.cc:30:8: note: built-in candidate operator==(double, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(double, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(long double, float) prog.cc:30:8: note: built-in candidate operator==(long double, double) prog.cc:30:8: note: built-in candidate operator==(long double, long double) prog.cc:30:8: note: built-in candidate operator==(long double, __float128) prog.cc:30:8: note: built-in candidate operator==(long double, long) prog.cc:30:8: note: built-in candidate operator==(long double, long long) prog.cc:30:8: note: built-in candidate operator==(long double, __int128) prog.cc:30:8: note: built-in candidate operator==(long double, unsigned int) prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long) prog.cc:30:8: note: built-in candidate operator==(long double, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(long double, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(__float128, float) prog.cc:30:8: note: built-in candidate operator==(__float128, double) prog.cc:30:8: note: built-in candidate operator==(__float128, long double) prog.cc:30:8: note: built-in candidate operator==(__float128, __float128) prog.cc:30:8: note: built-in candidate operator==(__float128, long) prog.cc:30:8: note: built-in candidate operator==(__float128, long long) prog.cc:30:8: note: built-in candidate operator==(__float128, __int128) prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned int) prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long) prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(__float128, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(long, float) prog.cc:30:8: note: built-in candidate operator==(long, double) prog.cc:30:8: note: built-in candidate operator==(long, long double) prog.cc:30:8: note: built-in candidate operator==(long, __float128) prog.cc:30:8: note: built-in candidate operator==(long, long) prog.cc:30:8: note: built-in candidate operator==(long, long long) prog.cc:30:8: note: built-in candidate operator==(long, __int128) prog.cc:30:8: note: built-in candidate operator==(long, unsigned int) prog.cc:30:8: note: built-in candidate operator==(long, unsigned long) prog.cc:30:8: note: built-in candidate operator==(long, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(long, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(long long, float) prog.cc:30:8: note: built-in candidate operator==(long long, double) prog.cc:30:8: note: built-in candidate operator==(long long, long double) prog.cc:30:8: note: built-in candidate operator==(long long, __float128) prog.cc:30:8: note: built-in candidate operator==(long long, long) prog.cc:30:8: note: built-in candidate operator==(long long, long long) prog.cc:30:8: note: built-in candidate operator==(long long, __int128) prog.cc:30:8: note: built-in candidate operator==(long long, unsigned int) prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long) prog.cc:30:8: note: built-in candidate operator==(long long, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(long long, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(__int128, float) prog.cc:30:8: note: built-in candidate operator==(__int128, double) prog.cc:30:8: note: built-in candidate operator==(__int128, long double) prog.cc:30:8: note: built-in candidate operator==(__int128, __float128) prog.cc:30:8: note: built-in candidate operator==(__int128, long) prog.cc:30:8: note: built-in candidate operator==(__int128, long long) prog.cc:30:8: note: built-in candidate operator==(__int128, __int128) prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned int) prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long) prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(__int128, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned int, float) prog.cc:30:8: note: built-in candidate operator==(unsigned int, double) prog.cc:30:8: note: built-in candidate operator==(unsigned int, long double) prog.cc:30:8: note: built-in candidate operator==(unsigned int, __float128) prog.cc:30:8: note: built-in candidate operator==(unsigned int, long) prog.cc:30:8: note: built-in candidate operator==(unsigned int, long long) prog.cc:30:8: note: built-in candidate operator==(unsigned int, __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned int) prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long) prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(unsigned int, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned long, float) prog.cc:30:8: note: built-in candidate operator==(unsigned long, double) prog.cc:30:8: note: built-in candidate operator==(unsigned long, long double) prog.cc:30:8: note: built-in candidate operator==(unsigned long, __float128) prog.cc:30:8: note: built-in candidate operator==(unsigned long, long) prog.cc:30:8: note: built-in candidate operator==(unsigned long, long long) prog.cc:30:8: note: built-in candidate operator==(unsigned long, __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned int) prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long) prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(unsigned long, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, float) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, double) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long double) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __float128) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, long long) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned int) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(unsigned long long, unsigned __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, float) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, double) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long double) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __float128) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, long long) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, __int128) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned int) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned long long) prog.cc:30:8: note: built-in candidate operator==(unsigned __int128, unsigned __int128) 1 error generated.
источник
Другое распространенное использование - это контейнеры std для сравнения на равенство ключевых значений внутри настраиваемых объектов.
class Foo { public: int val; }; class Comparer { public: bool operator () (Foo& a, Foo&b) const { return a.val == b.val; }; class Blah { std::set< Foo, Comparer > _mySet; };
источник
operator ()
notoperator bool
. Они совершенно разные.operator ()
- это оператор вызова, поэтому aComparer
можно вызывать как функцию. Этоoperator ()
просто происходитbool
, но это не делает его таким же, какoperator bool
, что просто позволяет неявное приведение кbool
.