Making copies of a type

How do you create copies of types? For example, how do I create types Mass

, Acceleration

and Force

that are implicitly convertible to double

(or any other numeric type), but otherwise have all the characteristics of a double

. This will allow compile-time input validation for this function:

Force GetForceNeeded(Mass m, Acceleration a);

      

so that GetForceNeeded

you can only call with arguments like 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 general solution?

+3


source to share


1 answer


As many commenters have pointed out, one solution is to use BOOST_STRONG_TYPEDEF , which provides all the functionality asked in the question. And here is a usage example 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 in C ++ 1y.

(I am leaving this answer because I cannot find the exact deception. Please note if this is not the case).

+5


source







All Articles