user2771184
user2771184

Reputation: 709

Can I prevent implicit conversion of an int typedef to int?

I'd like the following to not compile.

typedef int relative_index_t;  // Define an int to only use for indexing.
void function1(relative_index_t i) {
  // Do stuff.
}

relative_index_t y = 1; function1(y);  // I want this to build.
int x = 1; function1(x);               // I want this to NOT build!

Is there any way to achieve this?

Upvotes: 4

Views: 1881

Answers (2)

HolyBlackCat
HolyBlackCat

Reputation: 96166

You can't do that with typedef.

Use following instead:

enum class relative_index_t : int {};

Example usage:

int a = 0;
relative_index_t b;
b = (relative_index_t)a; // this doesn't compile without a cast
a = (int)b; // this too

Or following if you prefer C++-style casts:

int a = 0;
relative_index_t b;
b = static_cast<relative_index_t>(a);
a = static_cast<int>(b);

Also you can use BOOST_STRONG_TYPEDEF.
(Credits to @AlexanderPoluektov)

Upvotes: 8

wallyk
wallyk

Reputation: 57774

One technique borrow's from Modula-2's opaque types:

typedef struct {
              int  index;
        } relative_index_t;

That's probably good enough for preventing conversion with int. It also allows another member variable to allow additional features like age, sequence number generation, bounds checking, etc.

Upvotes: 0

Related Questions