Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why user-defined conversions are limited?

Tags:

c++

In C++, only one user-defined conversion is allowed in implicit conversion sequence. Are there any practical reasons (from language user point of view) for that limit?

like image 386
Paweł Bylica Avatar asked Jan 24 '14 16:01

Paweł Bylica


People also ask

What is user-defined conversion?

For more information, see Standard Conversions. User-defined conversions perform conversions between user-defined types, or between user-defined types and built-in types. You can implement them as Conversion constructors or as Conversion functions.

How many types of user-defined conversions are there?

There are two types of user-defined conversions: Conversion constructors and conversion functions.

What is user-defined conversion in C++?

User-defined conversions allow you to specify object conversions that are implicitly applied by the compiler, in addition to standard built-in type conversions.

Which operator can be used to do type conversions in C#?

Use the explicit conversion operator in C# The following code snippet shows how you can take advantage of the explicit operator to convert an Author instance to an instance of AuthorDto class.


1 Answers

Allowing only one user defined conversion limits the search scope when attempting to match the source and destination types. Only those two types need to be checked to determine whether they are convertible (non-user defined conversions aside).

Not having that limit might cause ambiguity in some cases and it might even require testing infinite conversion paths in others. Since the standard cannot require to do something unless it is impossible to do in your particular case, the simple rule is only one conversion.

Consider as a convoluted example:

template <typename T>
struct A {
   operator A<A<T>> () const;  // A<int> --> A<A<int>>
};

int x = A<int>();

Now, there can potentially be a specialization for A<A<A<....A<int>...>>> that might have a conversion to int, so the compiler would have to recursively instantiate infinite versions of A and check whether each one of them is convertible to int.

Conversely, with two types that are convertible from-to any other type, it would cause other issues:

struct A {
   template <typename T>
   A(T);
};
struct B {
   template <typename T>
   operator T() const;
};
struct C {
   C(A);
   operator B() const;
};

If multiple user-defined conversions where allowed, any type T can be converted to any type U by means of the conversion path: T -> A -> C -> B -> U. Just managing the search space would be a hard task for the compiler, and it would most probably cause confusion on the users.

like image 158
David Rodríguez - dribeas Avatar answered Oct 21 '22 02:10

David Rodríguez - dribeas