Quantcast
Channel: Intel® C++-Compiler
Viewing all articles
Browse latest Browse all 1665

Compiler error with explicit user-defined conversion for reference type

$
0
0

I'm having a problem compiling code where an explicit user-defined conversion operator isn't being found for a wrapper class. It happens when the wrapper class is storing a reference type

template<typename T>
class Wrapper
{
    private:
        int dummy_;
        T data_;

    public:
        Wrapper(T data) : data_(data) { dummy_ = 9999; }

        explicit operator T&()
        {
            std::cout << "In operator T&\n";
            return data_;
        }
};


int main(void)
{
    int i = 5;
    Wrapper<int &> wi(i);

    // Won't compile
    std::cout << "value: "<< static_cast<int &>(wi) << "\n";

    // Prints "9999", since it isn't calling Wrapper::operator T&()
    std::cout << "value: "<< (int &)(wi) << "\n";
    return 0;
}

 

In the above, the static_cast version won't compile (error: invalid type conversion: "Wrapper<int &>" to "int &"). The C-style cast compiles, but since the operator T& still isn't being called, the result is garbage, more or less.

Both versions work fine with g++ and clang. It works with Intel if the "explicit" is removed. Is this a bug?

EDIT: Actually, seems to happen even if the wrapper doesn't store a reference type (ie, Wrapper<int> wi(i) )


Viewing all articles
Browse latest Browse all 1665

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>