Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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?

like image 433
user2771184 Avatar asked Sep 06 '25 03:09

user2771184


1 Answers

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)

like image 72
HolyBlackCat Avatar answered Sep 07 '25 19:09

HolyBlackCat