C++ Logo

std-proposals

Advanced search

Re: [std-proposals] C++ feature ideea/proposal

From: Garrett May <garrett.ls.may_at_[hidden]>
Date: Tue, 5 Apr 2022 12:19:27 +0100
You can do the following with concepts in C++20:

#include <concepts>
#include <iostream>

template<std::same_as<int> T>
T RandomNumber(){
    return 7; // for simplicity
}

template<std::same_as<float> T>
T RandomNumber(){
    return 5.2; // for simplicity again
}

int main(){
    std::cout << RandomNumber<int>() << std::endl;
    std::cout << RandomNumber<float>() << std::endl;
    return 0;
}

which enforces a requirement on the template function.

The problem with casting is that RandomNumber() would have to deducible in
the first place, which it isn't as you don't know the return type ahead of
time. For example:

auto result = RandomNumber();

What would the type of result be? In other languages (like Rust), this
detail can be omitted until very late; but in C++, adding this could be
quite difficult.
If the aim is to simply be able to do (T)RandomNumber(), then I don't see
any advantage doing that over doing it via RandomNumber<T>() instead.

On Tue, 5 Apr 2022 at 12:00, Gašper Ažman via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> You can emulate that by returning a type with two conversion operators to
> the types you want.
>
> On Tue, Apr 5, 2022 at 11:59 AM PaulIRL via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> Hi, I'm currently learning C++ and at first I wondered why we can have 2
>> functions with the same name and different parameters but, not with the
>> same name, same parameters and a different return type, but probably this
>> is because the c++ compiler wouldn't know which function to call, however,
>> I think that a good solution is forcing the user (programmer) to cast the
>> output, and that way the compiler will know which function to call.
>> Example
>> int RandomNumber() {
>> return 7; //for simplicity
>> }
>>
>> float RandomNumber() {
>> return 5.2 //for simplicity again
>> }
>>
>> one could do
>>
>> std::cout<<(float)RandomNumber()<<std::endl; //prints 5.2\n
>>
>> however
>> std::cout<<RandomNumber()<<std::endl;
>> would throw a compiler error
>>
>> this would also work as expected
>> std::cout<<(int)(float)RandomNumber()<<std::endl; //prints 5\n
>>
>> - Paul Abrudan
>>
>> Trimis cu ProtonMail <https://protonmail.com/> e-mail securizat.
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2022-04-05 11:19:38