Reputation: 16777
How do you create type copies? For example, how do I create types Mass
, Acceleration
and Force
which are not implicitly convertible to double
(or any other numeric type), but otherwise have all the characteristics of a double
. This would allow a compile-time input validity check for this function:
Force GetForceNeeded(Mass m, Acceleration a);
ensuring that GetForceNeeded
can only be called with arguments of type Mass
and Acceleration
.
Of course, I could achieve this by manually creating a copy of the type:
class Force final
{
public:
//overload all operators
private:
double value;
};
but this is cumbersome. Is there a generic solution?
Upvotes: 3
Views: 141
Reputation: 16777
As many commentators have pointed out, one solution is to use BOOST_STRONG_TYPEDEF which provides all the features requested in the question. And here's example usage from their docs:
#include <boost/serialization/strong_typedef.hpp>
BOOST_STRONG_TYPEDEF(int, a)
void f(int x); // (1) function to handle simple integers
void f(a x); // (2) special function to handle integers of type a
int main(){
int x = 1;
a y;
y = x; // other operations permitted as a is converted as necessary
f(x); // chooses (1)
f(y); // chooses (2)
} typedef int a;
There is a proposal to add opaque typedefs to C++1y.
(I am leaving this answer as I can't find an exact dupe. Please flag if that isn't the case.)
Upvotes: 5