C++ - Class implicitly convertible to size_t

Viewed 64

I have created a simple class and I would like it to be convertible to size_t. But I don't understand how to do it.

class MyClass {
private:
    std::size_t size;
public:
    MyClass();
    ~Myclass();
};

I tried this got some errors :

Error: namespace std has no member class size_t

Thanks for your help in advance.

1 Answers

std::size_t can be found in multiple headers, for example <cstddef>

To enable the conversion, you can provide a operator std::size_t member function :

#include <cstddef>

class MyClass {
private:
    std::size_t size;
public:
    operator std::size_t() const {
        return this->size;
    }
    //...
};

the compiler will call the member function when needed:

int main() {
    MyClass foo;
    std::size_t s = foo;
}
Related