CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

F.16: GSL should provide a helper type alias template

Open gerlero opened this issue 1 year ago • 0 comments

F.16’s enforcement section prescribes that an “in” parameter to a function should be passed by copy when its type has a size less than 2*sizeof(void*), and by const reference otherwise.

@hsutter’s new cppfront project (which is an implementation of his C++ Syntax 2 proposal) shows that this rule can be applied programmatically in the current C++ syntax through the use of a clever type alias template, named cpp2::in in that project and defined here.

So, I’d like to propose that the Core Guidelines borrow this idea and specify a helper type alias template just like this as part of the GSL. Having such a definition readily available in the GSL would allow transparent application of this guideline directly in C++ code—even across different projects as long as the GSL spec is uniform and stable—which would be useful in a lot of cases (and particularly when writing generic code).

The utility of such an alias definition actually extends beyond "in" function arguments: it can also be used as a return type (e.g. in the definition of a getter function for accessing a member of unknown size). AFAICT the return case is not explicitly covered by a guideline (but could in the future; though there's a potential conflict with F.49's "Don't return const T" advice). Microsoft’s reference GSL implementation now defines such an alias for internal use as the return type of gsl::not_null’s get() member function, with the name value_or_reference_return_t. The more general name value_access was also suggested in that case by @hsutter, which I also think is very descriptive. For this reason, I don't propose adopting a name like gsl::in, but instead something more along the line of gsl::value_access (although I'd like something shorter given that it might appear multiple times in a function signature—I'm thinking of something like gsl::read, if we can accept the extra syntactic and semantic ambiguity that comes with that name).

gerlero avatar Nov 20 '22 19:11 gerlero