Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the compiler find the assignment operator?

template <typename T>
class MyPointer
{public:


    template <typename U>
    void operator=(MyPointer<U>&& other)
    {
      
    }
    char* get() const { return pointer; }
private:
    char* pointer;
};

int main()
{
    struct B {};
    struct D : B{};   

    MyPointer<B> my_pointer_b;
    MyPointer<D> my_pointer_d;

    my_pointer_b = my_pointer_d;


}

The error I get:

binary '=': no operator found which takes a right-hand operand of type 'MyPointermain::D' (or there is no acceptable conversion)

The compiler instantiates the assignment operator for the particular type that I use, so even if it deleted the default one the instantiated one should be there.

like image 408
Zebrafish Avatar asked Nov 08 '25 00:11

Zebrafish


1 Answers

Perhaps the error with gcc helps to shed more light on this:

<source>:24:20: error: cannot bind rvalue reference of type 'MyPointer<main()::D>&&' to lvalue of type 'MyPointer<main()::D>'
   24 |     my_pointer_b = my_pointer_d;
      |                    ^~~~~~~~~~~~

Your MyPointer<U>&& is not a forwarding reference. Its a rvalue reference.

From cppreference:

Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward. Forwarding references are either:

  1. function parameter of a function template declared as rvalue reference to cv-unqualified type template parameter of that same function template:
  2. [... auto&& ...]

This is a forwarding reference

template <typename T> void foo(T&&);

This one is not

template <typename T> void bar(X<T>&&);
like image 110
463035818_is_not_a_number Avatar answered Nov 09 '25 12:11

463035818_is_not_a_number