How can I create a new primitive type using C++11 style strong typedefs?

前端 未结 5 1528
醉梦人生
醉梦人生 2020-12-15 20:55

I\'m trying to emulate in C++ a distinct type from the Nim programming language. The following example won\'t compile in Nim because the compiler catches the variables

5条回答
  •  忘掉有多难
    2020-12-15 21:02

    There are several ways to solve this, but since I was looking for a fix to Bjarne's code in the presentation slides, I'm accepting this answer which @robson3.14 left in comments to the question:

    #include 
    
    template struct Unit { // a unit in the MKS system
        enum { m=M, kg=K, s=S };
    };
    
    template // a magnitude with a unit
    struct Value {
        double val; // the magnitude
        // construct a Value from a double
        constexpr explicit Value(double d) : val(d) {} 
    };
    
    using Meter = Unit<1,0,0>; // unit: meter
    using Second = Unit<0,0,1>; // unit: sec
    using Speed = Value>; // meters/second type
    
    // a f-p literal suffixed by ‘_s’
    constexpr Value operator "" _s(long double d)
    {
        return Value (d);
    }
    // a f-p literal suffixed by ‘_m’
    constexpr Value operator "" _m(long double d)
    {
        return Value (d);
    }
    // an integral literal suffixed by ‘_m’
    constexpr Value operator "" _m(unsigned long long d)
    {
        return Value (d);
    }
    
    template
    Value> operator / (Value> a, Value> b)
    {
        return Value>(a.val / b.val);
    }
    
    int main()
    {
        Speed sp1 = 100_m / 9.8_s;
        std::cout << sp1.val;
    }
    

提交回复
热议问题