EN VI

C++ - I want to know why the error occurred in the following code. Is it related to the type conversion operator??

2024-03-13 21:00:12
C++ - I want to know why the error occurred in the following code. Is it related to the type conversion operator?

I want to know why the error occurred in the following code. I use clang-17 for compilation. Compiling this code using gcc11.4.0 will also result in an error message I guess it should be related to the type conversion operator, but I cannot pinpoint the specific reason。


class A
{
public:
    template <class _Ty>
    explicit operator _Ty() const  noexcept
    {
        return c;
    }

    std::string c = "sdafasd";
};

int main()
{
    A a;
    const std::string &str = static_cast<const std::string &>(std::move(a));
}

I change the code to the following so that there will be no errors:

class A
{
public:
    template <class _Ty>
    explicit operator _Ty&() const  noexcept
    {
        return c;
    }

    std::string c = "sdafasd";
};

Why is this happening

Solution:

Because of how template argument deduction is specified (see: https://en.cppreference.com/w/cpp/language/template_argument_deduction#Conversion_function_template, Implications of conversion function template argument deduction in C++), _Ty isn't normally deduced as a reference type.

It's a similar logic as to why with template<typename T> void f(T x);, T x won't be deduced as a reference type.

Calling it manually will have the expected type:

const std::string &str = std::move(a).operator const std::string&();

But otherwise, to be able to convert to a reference type, you need to have &.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login