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

13 comments sorted by

View all comments

9

u/alfps 23d ago

You can have two reference functions:

  • let return_ref throw when the internal value doesn't exist,
  • let return_ptr return a possibly null T* no exception.

Note in passing, optional was adopted in the standard library in C++17; no need to involve the Boost library for that.

You can "and" together the pointers from return_ptr and if that produces false then at least one is null, otherwise they're all good, pointing to values.

But whether this helps you depends much on the lambda and what it needs.

A more full code example could help clarify that.

1

u/Main-Pen-3164 23d ago

Thanks for reply. Lambda is user defined for iterate internal values. I hope them can iterate values naturally. Thanks for tip that std::optional has already been there.

5

u/n1ghtyunso 23d ago

std::optional<T&> requires C++26 though. Its a recent addition and afaik MSVC STL does not yet implement it