-1

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.

  • 2
    Did you include the header for `std::size_t`? You'll also need a conversion operator: `operator std::size_t`. – HolyBlackCat Sep 21 '22 at 06:30
  • Yes I do. I put #include – Team もののけ姫 Sep 21 '22 at 06:34
  • Please create a proper [mre], then [edit] your question to copy-paste it into the question. Also please copy-paste the full and complete build-log from the shown example. – Some programmer dude Sep 21 '22 at 06:48
  • @Teamもののけ姫 Why is it not in the question? It should be. – HolyBlackCat Sep 21 '22 at 07:00
  • @Teamもののけ姫 The technical term for what you're looking for is *"conversion operator"*. Search that term and you'll find plenty of dupes and examples for this trivial task. For example, see [this answer](https://stackoverflow.com/a/71566446/12002570). Also refer to a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Sep 21 '22 at 08:17

1 Answers1

2

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;
}
Stack Danny
  • 7,754
  • 2
  • 26
  • 55