开发者

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

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) cons开发者_运维百科tructor. It's no wonder, this version was completely unrelated to ref.

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


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);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜