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