static_cast vs. direct call to conversion operator?

ぐ巨炮叔叔 提交于 2019-12-05 12:55:29

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.

No you never need to call the conversion operator member function directly.

If you use an instance of the class where a std::string object is expected then the conversion operator will be called automatically by the compiler, as will it if you use e.g. static_cast to cast an instance to std::string.

Simple and stupid example:

void print_string(std::string const& s)
{
    std::cout << s << '\n';
}

int main()
{
    point p(1, 2);

    print_string(p);  // Will call the conversion operator
    print_string(static_cast<std::string>(p));  // Will call the conversion operator too
}

The closest to call the function directly you will ever need is using something like static_cast.


In your specific case, with the output operator, then you should use static_cast. The reason is semantic and for future readers and maintainers (which might include yourself) of the code.

It will of course work to call the conversion member function directly (your option 2) but it loses the semantic information that says "here I'm converting the object to a string".

If the only use of the conversion operator is to use in the output operator, you might as well create a (private) function that takes the output stream reference as an argument, and writes directly to the stream, and call that function from the output operator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!