Discriminating between typedefs to same type in c+

2020-06-17 04:50发布

问题:

I want functionality similar to the below:

typedef int A;
typedef int B;


struct foo
{
  foo(A a) { /*specific to type A*/ }
  foo(B b) { /*specific to type B*/ }
};

I use the typedefs in my program to denote logically different usage of the same type. So, I would like to create object of type foo differently for different typedefs. I could compile this in g++, but msvc throws a fit saying that foo(A) is already defined when it sees the second definition foo(B). I thought of using a type list and the position of a type in the list to discriminate between the typedefs and tried using a boost::mpl::vector:

#include <boost/mpl/vector.hpp >
#include <boost/mpl/find.hpp>

typedef int A;
typedef int B;


struct foo
{
     typedef boost::mpl::vector<A, B> supported_types;

     foo(boost::mpl::find<supported_types, A>::type, A a) {}
     foo(boost::mpl::find<supported_types, B>::type, B b) {}
};

but unfortunately, find too discards my typedef and just returns iterator for A in both cases. I also thought about defining an enum and using it for each type

enum { TYPE_A, TYPE_B };
template <int i> struct int2type {};

and using this int2type and type B in the program. But this looks inelegant to me as it is prone to errors. I would like use a typelist and do this, so that it is clear what types would be supported.

Please let me know if there is a generic and extensible way of doing this.

回答1:

A boost strong typedef should do what you're looking for.

#include <boost/strong_typedef.hpp>

BOOST_STRONG_TYPEDEF(int, A);
BOOST_STRONG_TYPEDEF(int, B);


回答2:

Try BOOST_STRONG_TYPEDEF or implement your own: http://www.drdobbs.com/184401633;jsessionid=PNA3RR4N0WKFNQE1GHRSKH4ATMY32JVN