I use std::vector<int>
for two different kinds of information. I want to be sure that I don't accidentally mix the two uses.
In short, I want something like this piece of code to fail:
#include <vector>
using A = std::vector<int>;
using B = std::vector<int>;
void fa(const A&);
void fb(const B&);
void fun()
{
A ax;
B bx;
fa(bx);
fb(ax);
}
This code compiles, even though fa
expects an argument of type A
.
Obviously, A
and B
are identical.
What is the simplest way to make this code compile correctly:
fa(ax);
fb(bx);
and make this code fail:
fa(bx);
fb(ax);
Of course, I can wrap std::vector<int>
within another class, but then I'll need to rewrite its interface. Alternatively, I could inherit from std::vector<int>
, but this is frequently discouraged.
In short, I need two incompatible versions of std::vector<int>
.
EDIT
It has been suggested that Strong typedefs can solve this problem. This is only partially true. If I use BOOST_STRONG_TYPEDEF(std::vector<int>, A)
, I need to add some annoying casts. For example, instead of
A ax{1,3,5};
I need to use
A ax{std::vector<int>{1,3,5}};
And instead of
for (auto x : ax) ...
I need to use
for (auto x : (std::vector<int>)ax) ...
question from:
https://stackoverflow.com/questions/41300364/making-identical-c-type-aliases-incompatible 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…