Make an implicit conversion operator preferred over another in C++

社会主义新天地 提交于 2019-12-08 03:55:03

问题


I would like to prefer a certain implicit conversion sequence over another. I have the following (greatly simplified) class and functions:

class Whatever {...}

template <class T>
class ref
{
    public:

        operator T* ()
        {
            return object;
        }

        operator T& ()
        {
            return *object;
        }

        T* object;
        ...
};

void f (Whatever*)
{
    cout << "f (Whatever*)" << endl;
}

void f (Whatever&)
{
    cout << "f (Whatever&") << endl;
}

int main (int argc, char* argv[])
{
    ref<Whatever> whatever = ...;
    f(whatever);
}

When I have a ref object and I am making an ambiguous call to f, I would like the compiler to choose the one involving T&. But in other unambiguous cases I wish the implicit conversion to remain the same.

So far I have tried introducing an intermediate class which ref is implicitly convertible to, and which has an implicit conversion operator to T*, so the conversion sequence would be longer. Unfortunately it did not recognize in unambiguous cases that it is indeed convertible to T*. Same thing happened when the intermediate class had a(n implicit) constructor. It's no wonder, this version was completely unrelated to ref.

I also tried making one of the implicit conversion operators template, same result.


回答1:


Simple: define void f(const ref<Whatever>&), it will trump the others which require a conversion.




回答2:


There's no "ranking" among the two conversions; both are equally good and hence the overload is ambiguous. That's a core part of the language that you cannot change.

However, you can just specify which overload you want by making the conversion explicit:

f((Whatever&) whatever);



回答3:


Only one user-defined conversion function is applied when performing implicit conversions. If there is no defined conversion function, the compiler does not look for intermediate types into which an object can be converted.



来源:https://stackoverflow.com/questions/7327000/make-an-implicit-conversion-operator-preferred-over-another-in-c

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