Chaining implicit conversion operators

我只是一个虾纸丫 提交于 2019-12-23 18:35:55

问题


I've got a class which I need to implicitly convert to a few things, with intermediate values, e.g.

struct outer {
    struct inner {
        operator T() { return T(); }
    };
    operator inner() { return inner(); }
};

If I have this structure, is it always valid to do, e.g.

void f(T t);
outer o;
f(o);

回答1:


§13.3.3.1.2 [over.ics.user] p1

A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion (12.3) followed by a second standard conversion sequence.

Notice the singular and the missing of the word "sequence". Only one user-defined conversion will ever be considered during an implicit conversion sequence.




回答2:


This works:

struct Foo {}; // renamed T in Foo to avoid confusion!

struct outer {
        struct inner {
                operator Foo() { return Foo(); }
        };

        operator inner() { return inner(); }

        template <typename T>
        operator T () {
                return operator inner();
        }
};

int main() {
        void f(Foo t);
        outer o;
        f(o);
}

But only because f is not overloaded, so it is not really a solution.



来源:https://stackoverflow.com/questions/8610511/chaining-implicit-conversion-operators

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