User Defined Conversions in C++

我的梦境 提交于 2019-11-28 12:07:57

Is this a particularly obscure feature?

Yes, conversion operators aren't used very often. The places I've seen them are for user-defined types that can degrade to built-in ones. Things like a fixed-precision number class that supports converting to/from atomic number types.

Is this relatively portable?

As far as I know, it is. They've been in the standard forever.

Can user-defined conversions to user defined types be done?

Yes, that's one of the features of constructors. A constructor that takes a single argument effectively creates a conversion operator from the argument type to your class's type. For example, a class like this:

class Foo {
public:
    Foo(int n) {
        // do stuff...
    }
}

Let's you do:

Foo f = 123;

If you've used std::string before, odds are you've used this feature without realizing it. (As an aside, if you want to prevent this behavior, declare any single-argument constructors using explicit.)

It was about one of the first things I stumbled across when I was learning C++, so I'd say that no, it is not all that obscure.

One thing I would caution on though: Use the explicit keyword with them unless you know exactly what you are doing. Implicit conversions can cause code to behave in unexpected ways, so you should avoid using them in most cases. Frankly, I'd be happier if the language didn't have them.

CB Bailey

It's not particularly obscure; it is very portable (it is part of the language after all), and conversion to user-defined types is possible.

One word of caution, having a lot of possible implicit conversion paths can lead to unexpected conversion being invoked and surprising bugs. Also, having non-explicit converting constructors and conversion functions between several user-defined types can lead to more ambigious conversion sequeunces which can be a pain to resolve.

This is a particulary useful standard C++ feature and not a bit obscure :) You can use fundamental and user defined types alike for conversion operators.

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