C++ Logo

std-proposals

Advanced search

Re: [std-proposals] lambdas in enums

From: Jeremy Rifkin <rifkin.jer_at_[hidden]>
Date: Tue, 11 Mar 2025 21:23:44 -0500
Hi,
If all you want is a free function that looks like it is scoped in the
enum, do this:

namespace MyEnum {

enum Constant { A, B, C };

void my_function(Constant);

}

I don’t think you gain much from this sort of thing though.

Cheers,
Jeremy

On Tue, Mar 11, 2025 at 20:34 Dmitrii Shabalin via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi Andre.
> No, enum still an int.
> However, inside in the enum scope - enum class has a scope - it would have
> a static function.
>
> Kind regards,
> Dmitrii Shabalin.
>
> ср, 12 мар. 2025 г. в 12:30, Andre Kostur <andre_at_[hidden]>:
>
>> This seems to be ignoring that the underlying storage for the enum is
>> an int (of varying sizes). Now there needs to be an int, and
>> additional space for each lambda object that one might add. I'm not
>> seeing the immediate benefit over a normal free function.
>>
>> On Tue, Mar 11, 2025 at 4:20 PM Dmitrii Shabalin via Std-Proposals
>> <std-proposals_at_[hidden]> wrote:
>> >
>> > Hi.
>> > Since C++11 we have lambdas.
>> > I believe, everyone, who works with enums, write some functions for
>> this particular enum only.
>> > However, there is no way to associate this function with the enum's
>> namespace.
>> > My idea: we can set a value for any of enum fields. It should be const
>> and could be constexpr.
>> > May be, we can set a lambda for a field too?
>> > something like:
>> > enum Test{
>> > testValue = 0,
>> > toString =[](Test value) -> std::string { if (value == testValue)
>> return "testValue"; else return ""; },
>> > max = testValue
>> > }
>> >
>> > And usage will be something like:
>> > std::cout << "Test value" << Test::toString(Test::testValue);
>> > --
>> > 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 2025-03-12 02:23:56