r/programminghorror • • 9d ago

c++ Named nullptrs

Post image
402 Upvotes

50 comments sorted by

102

u/Nuclear_creeperMCBE 9d ago

C++ is a crazy language. Can anyone explain why you would ever want to overload what appears to be suffixed string literals.

33

u/Avelina9X 9d ago

EnTT uses it for hashed strings!

"my_string"_hs is the same as entt::hashed_string( "my_string" ), however the hashed_string class contains both compile-time and run-time storage, with a constexpr typecast operator to entt::id_type (a uint32_t) which returns the hashed value. This allows hashed string literals to be used as compile time arguments for anything which expects such an integral parameter, without needing a whole bunch of extra syntax.

For example, EnTT supports "tag" components inside its ECS registry. entt::tag<T> is simply an empty struct where T is in integral parameter, so if you wanna add a named tag to an entity you can write

myRegistry.emplace<entt::tag<"my_tag"_hs>>( myEntity );

And then later on if you want to create a view over components like entity positions or rotations or whatever if and only if they have that tag.

auto view = myRegistry.view<Position, Rotation, entt::tag<"my_tag"_hs>>()

13

u/Most-Bookkeeper-950 9d ago

this person appears to be cracked

9

u/Suitable_Plate4943 9d ago

the whole entt codebase has some of the nerdiest C++ ive ever seen to this day
bro has a nice blog too

8

u/Nuclear_creeperMCBE 9d ago

This is genuinely insane in the best way possible. Might start learning c++ just for this wierd features

4

u/Axman6 9d ago

People say Haskell is weird, and then go and choose to program in C++. I’ll never understand that, and I like writing the sort of code C++ is best at. 

3

u/Valuable_Leopard_799 8d ago

True, most of the languages that are touted as weird, unreadable, difficult, etc. by the mainstream are usually simple and force much much less congnitive load on you than C++. Haskell might be closer to C in difficulty than C++.

2

u/AnArmoredPony 8d ago

I wish there was a concept (or two) that would generalize this feature

1

u/2435191 8d ago

curious how Unix pipelines generalize this

1

u/AnArmoredPony 7d ago

"string" | hash

1

u/Ratstail91 8d ago

EnTT is kinda neat.

92

u/FloweyTheFlower420 9d ago

Out of all the horrible C++ features, user-defined literal suffixes is not one of them.

34

u/Nuclear_creeperMCBE 9d ago

Never said it was a bad feature just a bizzare addition. Like is typing "foo"custom_string that much better then custom_string("foo")

38

u/FloweyTheFlower420 9d ago

Yes, I'd much rather "xxx"_sv than invoke the string_view constructor. Less clutter. Also helpful for integer literal suffix (for units).

13

u/Mrblahblah200 9d ago

Yeah it actually is

-7

u/TOMZ_EXTRA 9d ago

It seems like a worse version of Rust traits which can achieve a very similar result (for example 5.ms())

21

u/sr9zzek2y 9d ago

std::chrono defines custom suffix operators for it's durations, so if you want to check if a duration is over 5ms, you do duration > 5ms

3

u/Rararror 9d ago

This is nice

7

u/Qwexet 9d ago

One usecase is if you write your own string class. You can also make user defined literals with numbers

6

u/Pie-Lang 9d ago

“Name”_human
vs
Human{“Name”}

pick your references.

5

u/Nuclear_creeperMCBE 9d ago

Is there a semantic difference or is it purely syntactic

6

u/_Ilobilo_ 9d ago

std::string_view { "hello" } vs "hello"sv

1

u/conundorum 5d ago

Mainly syntactic. It's intended to match integer suffixes like 123u or 456LL, to make the code more intuitive.

It's nice for custom integer types, since it lets their syntax match the fundamental types. (And for size_t, since it's baffling that we got the suffix operator in C++14, but had to roll our own size_t suffix for almost a decade.)

MyInt<int> operator""_MI(long double i) { return i; }
MyInt<unsigned> operator""_mu(long double i) { return i; }

auto i = 123_MI;
auto j = 456u;
auto k = 789_mu;

It's useful for string types, since it lets us cleanly turn on string semantics and reduces redundancy.

auto str = std::string("lorem") + ' ' + "ipsum"; // Blech.
auto ing = "lorem"s + ' ' + "ipsum"; // Simple & clean.

It lets complex numbers actually look like real math now.

std::complex old{4, 5};
std::complex new = 4 + 5i;

And it's extremely useful for long-winded names like the various std::chrono units.

auto star_wars = std::chrono::hours(2) + std::chrono::minutes(1);
auto empire_sb = 2h + 4min;

It's just a special function (usually, but technically not required to be, a conversion operator), but designed so that its syntax feels like a natural evolution of integer suffixes.

2

u/S4N7R0 9d ago

Commitee likes converting string literals to string_view wit it https://en.cppreference.com/cpp/string/basic_string_view/operator%22%22sv

1

u/ice456cream 9d ago

I mean js has tagged string literals tag`value` which runs tag as a template

1

u/conundorum 5d ago edited 5d ago

To parallel integer suffixes, basically. We can use, e.g., 123u to say that we want 123 to be an unsigned int instead of a bog-standard int, which allows us to automatically force an expression into unsigned-ness without needing to cast anything.

int i = 123;
unsigned u1 = (unsigned) i + 456;
unsigned u2 = (unsigned) 123 + 456;
unsigned u3 = 123u + 456;

This turns out to be really helpful, which is why it was a language feature from the start. What was less obvious, though, was that it would be just as helpful to have a way to do the same thing with character literals and std::string, because a very basic operation (string addition) has extremely different functionality depending on what type of string we're working with. (We really don't want to accidentally use pointer arithmetic when we wanted to concatenate two C strings, after all! And it gets really messed up when one or both of the strings is const.) So, they added literal operators as a way to cleanly construct a string around a character literal mid-expression, to turn on std::string semantics with minimal extra typing & redundancy.

std::string hi = std::string("hello") + ' ' + "world"; // Longer & redundant.
std::string hw = "hello"s + ' ' + "world"; // Simple & clean.

That's good by itself, but there are a lot of custom string types out there, so they decided to let us make our own suffixes, too. (Especially since making a compile-time equivalent to std::string was a big thing when C++11 came out, and they wanted to be ready for that. They still weren't ready, funnily enough, since compile-time string types ended up being template wizardry instead.)

They also realised that it would be useful in certain math contexts, where basic math expressions were inexpressible because of language deficiencies. Like, say, complex numbers; it was impossible to just write 3 + 2i and expect the compiler to understand. So, they provided suffix operators for the imaginary part of std::complex, too.

std::complex c1{3, 2}; // Old-school.
std::complex c2 = 3 + 2i; // Sane-school.

...And also provided a pile of literals for time & date, to help people use saner syntax there, too.

auto star_wars = std::chrono::hours(2) + std::chrono::minutes(1);
auto empire_sb = 2h + 4min;

...And realised that there were a lot of contexts where people would want (or already desperately wanted) suffixes that didn't exist yet, so they let people roll their own. For numeric types, it would let everyone provide a size_t suffix, and would let anyone who made a custom integer class provide a clean suffix for their type. (It's honestly kinda baffling that it took until C++23 to get a suffix for size_t, and we had to make our own until then.) For strings, it would let anyone that make a custom string type provide their own suffix, too. And so on.


Essentially, they realised that letting us make little blobs of ugliness in one place would make the rest of the code both cleaner, and easier to read. It's just a convenience, ultimately, but it's easy to underestimate just how convenient it is.

3

u/Ben-Goldberg 9d ago

I could see the use case of a generic class which returns the nullptr when cast to a pointer, so that compiler errors have the names of the type(s) you have attached to the error message, but I am pretty sure that OP's code doesn't do that.

4

u/Avelina9X 9d ago

It indeed does not do that. I just wanted a way to write a "comment" inside a nullptr argument. Some sort of way to self document why the nullptr is there :)

1

u/Ben-Goldberg 9d ago

Like writing assert("comment")?

1

u/conundorum 5d ago

You can also do this by declaring varaibles of type std::nullptr_t, since it's implicitly convertible to any pointer type. That's not as flexible as a null suffix, though.

#include <cstddef>

constexpr std::nullptr_t placeholder = nullptr;
// ...
inline constexpr void *placeHolder = placeholder;

212

u/KGBsurveillancevan 9d ago

Every time I see C++ code posted here I see some syntax I’ve never seen before

50

u/Axman6 9d ago

C++ syntax is fractal, everywhere there’s syntax, more syntax gets added. For example:  https://youtu.be/EqiLTgQcDPM

44

u/johntheswan 9d ago

c++ contains multitudes

3

u/conundorum 5d ago

It's the suffix operator ("user-defined literal" operator, or operator""_whatever) syntax, it lets you create a type converter that can be used like a standard syntax. Operator name is two quotation marks, an underscore, and a name, with no spaces at any point. The underscore technically isn't required, just mandated; underscore-less suffixes are reserved for the language, so it's an error to make your own. (Notably, I believe this is the one and only time that the "no underscore followed by capital" rule is waived, since operator""_Z is explicitly called out as valid if you want to roll your own size_t suffix. Double underscores are still a no-go, tho'.)

It parallels the integer literal suffixes (unsigned 123u, long long 456ll, etc.), by letting you provide literals for other conversions too. For example, the official "this is a std::string"s (the trailing s converts to string) and "this is a string_view"sv, or 7.89i (the trailing i creates a std::complex with 0.0 real & 7.89 imaginary), or a big pile tied to std::chrono for dates & times.

1

u/KGBsurveillancevan 5d ago

That’s actually pretty interesting and kinda makes sense

52

u/No_Belt_9829 9d ago

Absolute horrid, darling

26

u/W00GA 9d ago

i didn't know "fucked up shit" was a language

14

u/Sacaldur 9d ago

So you implemented an overload that lets you take a string literal, just to ignore it? The title ("named nullptr") might hint at the fact that this null now has a name, but afaik (not the best C++ Dev though) that at most helps while reading the code, but for this you could also use the variable name or a comment and it would have the same result (except being easier).

6

u/AmazedStardust 9d ago

Does this just let you type "placeHolder" instead of "nullptr"?

2

u/GoddammitDontShootMe [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live" 9d ago

I have no clue what possible purpose this could serve.

1

u/conundorum 5d ago

Labeling, mainly. Looks like it's meant to be self-documenting code, for "placeholder null".

1

u/blockMath_2048 9d ago

wait wtf that’s a thing?????

1

u/Antagonin 8d ago

Why not use comments?

1

u/uvero 6d ago

All C++ makes me smell toast tbfh

1

u/Aaxper 5d ago

but... why?

1

u/NamedBird 9d ago

In C, name one of your variables "nullptr", just because you can.
Then when a C++ dev tries to use your code, you can watch the resulting fire... 🤣

2

u/Wenir 9d ago

just because you can

You can't 

4

u/NamedBird 9d ago

you can though?
It's a valid string to use as variable.

"nullptr" is only a reserved keyword in the newest unstable C23 version...
https://en.cppreference.com/c/language/nullptr

4

u/Wenir 9d ago

unstable

Anything released in this millennium is too old?

2

u/NamedBird 9d ago

We're in r/programminghorror, anything released yesterday is considered unstable...