Making auto_cast safe

前端 未结 3 512
长情又很酷
长情又很酷 2021-02-05 19:09

GMan has posted a code for the delicious auto_cast “operator” that allows to write code such as the following in C++:

float f = 4.0f;
int i = auto_cast(f);
// in         


        
3条回答
  •  广开言路
    2021-02-05 19:58

    It appears you want to use the T{u} form of initialization.

    template 
    operator U()
    {
        return U{std::forward(mX)};
    }
    

    One of the reasons for these uniform initialization was that to use explicit constructors for creating a temporary, you need a cast aka T(u). With T{u} that problem was solved. For C++03, I imagine you could do something like this:

    template
    struct construct_explicit {
      template
      construct_explicit(U &u):t(u) { }
      template
      construct_explicit(U const &u):t(u) { }
    
      T &get() { return t; }
      T const& get() const { return t; }
    
      T t;
    };
    

    Then you can say construct_explicit(mX).get(), although in a case like in your conversion function, it also works to use a named variable as an intermediary step, I think

    template 
    operator U()
    {
        // or C++03: U u(mX);
        U u(std::forward(mX));
        return u;
    }
    

提交回复
热议问题