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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With