Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static_cast vs. direct call to conversion operator?

Consider the following class, just as a simple example:

#include <iostream>
#include <string>
using namespace std;

class point {
public:
    int _x{ 0 };
    int _y{ 0 };

    point() {}
    point(int x, int y) : _x{ x }, _y{ y } {}
    operator string() const
        { return '[' + to_string(_x) + ',' + to_string(_y) + ']'; }

    friend ostream& operator<<(ostream& os, const point& p) {

        // Which one? Why?
        os << static_cast<string>(p); // Option 1
        os << p.operator string();    // Option 2

        return os;
    }
};

Should one call a conversion operator directly, or rather just call static_cast and let that do the job?

Those two lines will pretty much do exactly the same thing (which is to call the conversion operator), there's no real difference between their behavior as far as I can tell. So the real question here is whether that's true or not. Even though these seem the same to me, there could still be subtle differences that one might fail to pick up on.

So are there any practical differences between those approaches (including ones that might not apply to this example), other than the fact that the syntax for them different? Which one should be preferred and why?

like image 724
notadam Avatar asked Mar 12 '23 02:03

notadam


1 Answers

So are there any practical differences between those approaches

In this case, not that I know of, behaviour wise.

(including ones that might not apply to this example)

static_cast<X>(instance_of_Y) would also allow conversion if X has a converting constructor for the type Y. An explicit call to (possibly non-existent) conversion operator of Y could not use the mentioned converting constructor. In this case of course, std::string does not have a converting constructor for point.

So, the cast is more generic and that is what I would prefer in general. Also "convert this object to type string" is more meaningful than "call the operator string()". But if for some very strange reason you want to avoid the converting constructor, then explicit call to conversion operator would achieve that.

like image 60
eerorika Avatar answered Mar 23 '23 03:03

eerorika