Search code examples
c++type-conversionc++17static-castexplicit-conversion

Require operator double() to be explicitly called via static_cast<double>(x)


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


Solution

  • 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);