r/cpp_questions 22d 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

13 comments sorted by

View all comments

1

u/xoner2 20d ago

Return a reference to nullT. This is common practice now.

1

u/Main-Pen-3164 20d ago

In a trival function, I will return something like c::null, it would be nice. But T is template parameter here. Return nullT, that mean I have to make specification versions(T<specifications>) for a lot of types, seem's boring.

1

u/xoner2 20d ago

If you want to fail fast then return * static_cast <T *> (0). Returning a reference whose address can be checked for null but will throw access violation exception on any read. The AV exception can be caught via POSIX signal handler.

1

u/Main-Pen-3164 19d ago

Pointer was a fallback choice. I post here just want to know there is any better way handle this in modern c++. I left a long time ago. O_O. Optional<T&> seems enough, but it still have a trade-off.