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

前端 未结 5 1525
醉梦人生
醉梦人生 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:04

    Not sure this is what you want, it is ugly, but it works :) You can wrap the type into a template class,

    template  // N is used for tagging
    struct strong_typedef
    {
        using strong_type = strong_typedef; // typedef for the strong type
        using type = T; // the wrapped type
        T value; // the  wrapped value
    
        strong_typedef(T val): value(val){}; // constructor
        strong_typedef(){value={};}; // default, zero-initialization
    
        // operator overloading, basic example: 
        strong_type& operator+(const strong_type& rhs)
        {
            value+=rhs.value; 
            return *this;
        }
    
        // display it
        friend ostream& operator<<(ostream & lhs, const strong_typedef& rhs)
        {
            lhs << rhs.value;
            return lhs;
        }
    };
    

    then use it as

    // these are all different types
    strong_typedef x = 1.1; 
    strong_typedef y = 2.2;
    strong_typedef z = 3.3;
    
    std::cout << x + x << std::endl; // outputs 2.2, can add x and x
    // cout << x + y << endl; // compile-time ERROR, different types
    

    x, y and z are 3 different types now, because of the different N-s used in the template. You can access the type and value using the fields type and value, like x::value (will be double 1.1). Of course if you directly typedef the struct_typedef::type, you're back to square one, as you are losing the strong type. So basically your type should be strong_typedef and not strong_typedef::type.

提交回复
热议问题