简体   繁体   中英

Typecast overloading

I could overload '+' operator but I am not sure how I could typecast for the NewType. I would like it to be typecasted to any other variable type. Can you please provide some pointers? Thanks a lot!

#include <iostream>

class NewType {
private:
  float val;

public:
  NewType(float v) { val = v; }
  friend NewType operator+(const NewType &c1, const NewType &c2);
  float GetVal() const { return val; }
};

NewType operator+(const NewType &c1, const NewType &c2) { return NewType(c1.val + c2.val); }

int main() {
  NewType a = 13.7;
  // Here is the problem, I would like this to print 13.
  std::cout << (int) a << std::endl;
  return 0;
}

I would like it to be typecasted to any other variable type.

For any other variable type you need a templated user-defined conversion:

class NewType {
public
// ...
   template<typename T>
   explicit operator T() const { return T(val); } 
// ...
};

explicit (here C++11 and up) makes sure you will use explicit cast, ie:

NewType a = 13.7;
int n = a; // compile error
int n2 = static_cast<int>(a); // now OK

You could also use uniform initialization in your user-defined conversion operator:

   template<typename T>
   explicit operator T() const { return T{val}; } 

this will give you additional warning in case your cast could require narrowing. But as I see under gcc this generates only warnings by default (as I remember this is by design - due to lots of legacy code would break), under clang it generates error:

main.cpp:15:16: error: type 'float' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]
      return T{val}; 

and the same Visual Studio generates error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM