Почему мой & quot; явный оператор bool () & quot; не называется?

#include <iostream>

using namespace std;

struct A
{
explicit operator bool() const
{
return true;
}

operator int()
{
return 0;
}
};

int main()
{
if (A())
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}

Я ожидал, что A() будет контекстно преобразован в bool используя мой operator bool()и, следовательно, распечатать true,

Тем не менее, выход false, показывая, что operator int() был вызван вместо

Почему мой explicit operator bool не называется, как ожидалось?

7

Решение

Так как A() не является const, operator int() выбран. Просто добавь const другому оператору преобразования, и это работает:

#include <iostream>

using namespace std;

struct A
{
explicit operator bool() const
{
std::cout << "bool: ";
return true;
}

operator int() const
{
std::cout << "int: ";
return 0;
}
};

int main()
{
if (A())
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}

Живой пример что печатает: «bool: true» и без const он печатает «int: false»

Или создайте именованную константу:

// operator int() without const

int main()
{
auto const a = A();

if (a)
// as before
}

Живой пример это печатает «bool: true».

15

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector