Can you use keyword explicit to prevent automatic conversion of method parameters?

后端 未结 8 1526
心在旅途
心在旅途 2020-12-04 17:18

I know you can use C++ keyword \'explicit\' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion

8条回答
  •  旧时难觅i
    2020-12-04 18:05

    The following is a very basic wrapper that can be used to create a strong typedef:

    template  
    class StrongType
    {
    public:
      inline explicit StrongType(V const &v)
      : m_v(v)
      {}
    
      inline operator V () const
      {
        return m_v;
      }
    
    private:
      V m_v; // use V as "inner" type
    };
    
    class Tag1;
    typedef StrongType Tag1Type;
    
    
    void b1 (Tag1Type);
    
    void b2 (int i)
    {
      b1 (Tag1Type (i));
      b1 (i);                // Error
    }
    

    One nice feature of this approach, is that you can also distinguish between different parameters with the same type. For example you could have the following:

    class WidthTag;
    typedef StrongType Width;  
    class HeightTag;
    typedef StrongType Height;  
    
    void foo (Width width, Height height);
    

    It will be clear to the clients of 'foo' which argument is which.

提交回复
热议问题