Joseph Caruso
Joseph Caruso

Reputation: 185

C++ custom type

I've got a class int32, and it is set up in a way that it can essentially be interfaced with as an int (operator overloads), but there's one part I don't get.

int32 i32 = 100; // Works
int i = 200; // Works
i32 += 10; // Works
i32 -= 10; // Works, i32 = 100 right now
i = i32; // Doesn't work

What operator would I need to overload to achieve referencing i32 returning it's stored value, in this case, 100 (or how else could it be done)?

Upvotes: 1

Views: 2548

Answers (3)

Tasawar Hussain
Tasawar Hussain

Reputation: 765

Implement a conversion operator on your int32 class.

class int32
{
    // conversion operator
    operator int() const
    { 
        int ret = // your logic
        return ret;
    }
}

This conversion operator will convert primitive type (int) to your defined type int32;

Upvotes: 1

yumetodo
yumetodo

Reputation: 1202

class int32{
private:
    std::int32_t value;
public:
    constexpr /*explicit*/ operator std::int32_t() const noexcept { return this->value; }
};

You should write conversion operator.

int32 a = 1;
std::int32_t b = a;//OK

However, it is harmful so that specify explicit and force cast to convert.

int32 a = 1;
//std::int32_t b = a;//NG
std::int32_t b = static_cast<std::int32_t>(a);

note: You shold not write conversion operator to int because there is no guarante int is 32bit.

Upvotes: 2

Ami Tavory
Ami Tavory

Reputation: 76297

You could add a conversion operator operator int:

class int32 {
public:
    operator int() const;
    ...
};

Note that it comes in two flavours. The above will allow

int32 foo;
int i = foo;

If you define the conversion operator as explicit

    explicit operator int() const;

then the above will fail by design, and require an explicit cast:

int32 foo;
int i = static_cast<int>(foo);

Upvotes: 8

Related Questions