C++ Logo

std-proposals

Advanced search

[std-proposals] Pass derived object by reference to single parameter delegated templated constructors

From: David wang <wangjufan_at_[hidden]>
Date: Wed, 8 May 2024 22:36:53 +0800
On Tue, 7 May 2024 10:31:46 -0400 Jason McKesson via Std-Proposals
<std-proposals_at_[hidden]> wrote:

>But it *is* the user's fault.

>The writer of the base class wrote a constructor with a template that
>uses template argument deduction for a value parameter. Outside of
>tools like `std::ref`, this makes it functionally impossible for this
>function to be instantiated with `T` as a reference type. We must
>therefore assume that the code inside that constructor *will not work*
>if `T` is a reference type.

>The writer of the derived class wants to call this constructor with a
>reference type. A thing that this constructor was written to
>explicitly disallow cannot happen and can cause it to fail.

>The desires of one user conflicts with the desires of the other. When
>user desires are conflicting, it's the users who must sort them out,
>not the language.

`std::ref` still can be instantiated with `T`(for example struct derived)
as a reference type.
No conflicts occurred between users.
It is the conflict between function matching rules and passing objects by
reference to the copy constructor.

#include <functional>

*template* <*typename* T>

*void* bindRefTest(T& value) {}

*struct* base {

  *public* : base() {}

  *template* <*typename* T> base(T x) {}

};

*struct* derived : *public* base {

  *public*: derived() {}

  derived(derived& that): base(that) {}

};

*int* main() {

  derived d1;

  derived d2 = d1;

  *auto* func = std::bind(bindRefTest<derived>, std::ref(d1));

  func();

  *return* 0;

}

Received on 2024-05-08 14:37:06