为什么用户定义的转化有限? [英] Why user-defined conversions are limited?

查看:111
本文介绍了为什么用户定义的转化有限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

推荐答案

只允许一个用户定义的转换限制尝试匹配源和目标类型时的搜索范围。只有这两种类型需要检查,以确定它们是否可转换(非用户定义转换)。

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.

考虑一个复杂的例子:

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

int x = A<int>();

现在,可能有一个专门化 A< A< A< .... A< int> ...>>> 可能会转换为 int 递归地实例化 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;
};

如果允许多个用户定义的转换,任何通过转换路径转换为任何类型U:T - > A - > C - > B - > U。只是管理搜索空间对于编译器来说是一个艰巨的任务,并且很可能导致用户。

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.

这篇关于为什么用户定义的转化有限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆