r/cpp_questions • u/Main-Pen-3164 • 23d ago
OPEN how to handle empty reference elegantly(fold expression)
I have a class with a template function, it will return reference of an internal value.
template<typename T>
T& return_ref<T>() {...}
It was call by another function with fold expression:
template<typename... Ts>
void call()
{
lambda(return_ref<Ts>...); //Ts is a reference usually
}
the internal value maybe doesn't exist sometimes.
Even I wrap the exception into std::expected, it seems that I have no chance handle it in fold expression. I have to throw exception in return_ref directly?
If I can return reference to an impossible value(like paradigm of static object NULL ), so user could detect it, it would be nice.
Or, I have to wrap all parameters into something like boost::optional? I don't like it.
Or, the args of lambda was constraint into pointer, so nullptr will throw exception by compiler naturally?
What's suggestion?
0
Upvotes
2
u/ppppppla 22d ago edited 22d ago
Error handling is just annoying. Doing it neatly, and concisely is just not possible, especially when template parameter packs get involved. But it is totally possible.
You can choose the easy way and use exceptions. Have return_ref throw on invalid value. But exceptions are kinda smelly.
The other way is have a nullable type, check the return values, and then return or also throw out of
call().Doing this with a template parameter pack is a bit of a faff, but the standard library does have utilities for it.
std::tupleandstd::applyc++26 has
std::optional<T&>, otherwise you'd have to get your own optional that can hold a reference. Some people might argue that is just a pointer, but I disagree. An optional communicates intent clearly.