Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.
7957 Discussions

Compiler error with explicit user-defined conversion for reference type

Pritchard__Ben
Beginner
392 Views

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

0 Kudos
3 Replies
Feilong_H_Intel
Employee
392 Views

Hi Ben,

I entered this issue to our problem-tracking database.  Engineering team will look into it soon.

Thanks.

0 Kudos
Judith_W_Intel
Employee
392 Views

 

Yes it looks like GNU and Clang have implemented the resolution to this Core Language issue:

http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1392

and Intel has not done so yet.

In the meantime removing the "explicit" should fix the problem (and hopefully not cause unwanted conversions).

Judy

 

0 Kudos
Pritchard__Ben
Beginner
392 Views
Thanks for the link and for looking into this. I did discover that removing 'explicit' was a fix in my case, and didn't cause any undesired behavior.
0 Kudos
Reply