2

I'd like to enable conversion of my class to a double value. This can be achieved by overloading operator double() but this then allows for implicit conversion, which ideally I'd like to be able to avoid.

Is there any way to add this functionality but with the requirement that conversions are made using double y = static_cast<double>(x) rather the implicitly being made; double y = x?

I'm using C++17. Thanks

Arc
  • 139
  • 6
  • 2
    By using the [*`explicit`*](http://en.cppreference.com/w/cpp/language/explicit) keyword for your [user-defined conversion operator](http://en.cppreference.com/w/cpp/language/cast_operator)? – Some programmer dude Nov 02 '17 at 21:45
  • @user0042 (a) constructors, not "constructor functions" (b) not [since C++11](http://en.cppreference.com/w/cpp/language/explicit) – Barry Nov 02 '17 at 21:47
  • This is one of those rare cases when C++ declaration syntax makes sense. – user7860670 Nov 02 '17 at 21:50
  • @VTT: what do you mean, can you explain please? – geza Nov 02 '17 at 21:56
  • @geza I mean that to make some user-defined conversion function explicit one needs to use `explicit` keyword instead of some gibberish. – user7860670 Nov 02 '17 at 21:58
  • @VTT: ah, okay :) – geza Nov 02 '17 at 22:01
  • This question uses terminology correctly. It is unfortunate that the title of the question cited as a duplicate refers to the non-existent "cast operator". It is a **conversion operator**. – Pete Becker Nov 02 '17 at 22:22

2 Answers2

2

Yes, you can mark conversion operators explicit since C++11.

explicit operator double() { /* ... */ }

This will prevent copy-initialization, e.g.,

double y = x;
return x;  // function has double return type
f(x);  // function expects double argument

while allowing explicit conversions such as

double y(x);
double y = static_cast<double>(x);
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thank you. It did not occur to me that the explicit keyword would effect the static_cast operator. Cheers! – Arc Nov 02 '17 at 21:48
1

Use explicit:

struct X {
    explicit operator double() const { return 3.14; }
};

double y = static_cast<double>(X{}); // ok;
double z = X{}; // error
Barry
  • 286,269
  • 29
  • 621
  • 977