C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Function overload set type information loss

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 31 Jul 2024 18:46:47 -0400
On Wed, Jul 31, 2024 at 6:40 PM organicoman via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
>
>
> Another thing, we keep hearing about how we need this proposal because “this isn’t how type theory works,” but this is not true, and is a misunderstanding of both how C++ implements types and of type theory itself.
> First off, if you want a really type-theory savvy language, you should probably be using Idris or Haskell or Coq, not C++. But the fundamental misunderstanding seems to be that a template instantiation is a dependently typed function.
>
> ```cpp
> template<typename T>
> int X(int) { /* ...*/ }
> ```
> It is not. The type of any specialization of this “function" is not
> * -> int -> int,
> because this is not a function at all, it is a template of how to create a function. For any specialization (e.g. X<int>, X<bool>, etc), the type of the resulting functions is just
> int -> int.
>
> This is called a mapping from int to int that means, if two functions stamped from the same template have the same mapping, then the same input gives the same output.
> But with current C++ it is not the case.
> Example:
> template<int I>
> int foo (int j)
> {
> return I * j;
> }
>
> int main()
> {
> auto f1 = &foo<5>;
> auto f2 = &foo<-3>;
>
> if(std::is_same_v<decltype(f1), decltype(f2)>)
> cout << " f1(1) must equal f2(1) is" << boolalpha<< (f1(1)==f2(1));
> }
>
> Try this snippet, and reason about it. That's all what i can say.

But `foo<5>` and `foo<-3>` do not "have the same mapping" of `int` to
`int`. As such, there is no reason to expect `f1(1)` and `f2(1)` to be
equal.

Two instantiations of the same template with different parameters
generate different things. That's *how templates work*.`foo<5>` and
`foo<-3>` are expected to be different functions with different
behavior. Two different functions that have the same type are still
*two different functions*.

Received on 2024-07-31 22:47:00