error: bool' cannot be declared with 'explicit' specifier

So when i use the explicit with bool to convert a parameter i get this

error : " error C2178: 'sdds::Ship::operator bool' cannot be declared with 'explicit' specifier."

My objective with this function was to use it to convert a bool operator that returns true if the object is valid , and false otherwise.

1
2
3
4
5
6
7
8
9
explicit Ship::operator bool() const
    {
        bool check = true;
        if (m_type == nullptr && strlen(m_type) == 0 && m_engines[0].get() > 0 && m_engCnt == 0)
        {
            check = false;
        }
        return check;
    }


Here is my class

1
2
3
4
5
6
7
8
class Ship
    {
        Engine m_engines[10];
        char m_type[TYPE_MAX_SIZE];
        int m_engCnt;
... public:
explicit operator bool() const;
...
1. The explicit keyword cannot be applied to an out-of-line definition.
For example
1
2
3
4
struct A { explicit operator bool() const noexcept; };

/* explicit must not appear here */ 
A::operator bool() const noexcept { return true; }


2. explicit conversion operators are a feature added in C++11.
To work around the second (potential) issue in legacy C++, consider implementing an implicit conversion operator to void* instead, i.e., using the now-outdated safe-bool idiom
https://www.artima.com/cppsource/safebool.html
Last edited on
Topic archived. No new replies allowed.