vendredi 23 décembre 2016

Making identical C++ classes incompatible

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>.

Aucun commentaire:

Enregistrer un commentaire