LIU Qingyuan
LIU Qingyuan

Reputation: 586

in C++ , can I define an implicit conversion to a class without modifying the class?

Recently I have to work with some C libraries in my C++ code. The C library I am using defined a complex number class as follow:

typedef struct sfe_complex_s
{
    float real;
    float img;
} sfe_complex_t;

Naturally I do not want to work with this C-style data structure in C++, so for convenience I want to define an implicit conversion from this type to std::complex<float>. Is there a way to do so? Or I have to explicitly do the conversion?

Upvotes: 1

Views: 1422

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 596156

No, you cannot define an implicit conversion between types that you don't have access to change. Your only option will be to define your own function that explicitly takes a sfe_complex_t as input and returns a std::complex<float> as output.

Upvotes: 0

n314159
n314159

Reputation: 5075

An implicit conversion can only take place in a constructor of the class converted to or a conversion operator of the class converted from, which has to be a member function. Since you cannot modify either one, you are out of luck.

It may be appealing to define an own class with implicit constructors from and conversion operators to both std::complex<float> and sfe_complex_t, but this will not give you implicit conversions between these two clases, since user defined conversions cannot be chained. You could a class defined in this way in your code and it would always be converted implicitly if you put it somewhere either of the others are expected, but you should really consider if that is what you want. It would introduce another standard and make your code less readable.

To me, it seems like calling an explicit conversion is the cleanest variant. Depending on the number of functions of your C library you could perhaps for each one provide an overload taking std::complex and explicitly converting it before passing it on.

Upvotes: 0

Nicol Bolas
Nicol Bolas

Reputation: 473407

Implicit conversion is supposed to mean something. It represents a strong relationship between the source and destination types of that conversion. That one of them is, on some level, designed to be equivalent to another in some degree.

As such, only code which is intimately associated with either the source or destination type can define that relationship. That is, if you don't have control over the source or destination types, then C++ doesn't feel that you are qualified to create an implicit conversion relationship between them.

3rd parties cannot make types implicitly convertible.

Upvotes: 2

Related Questions