cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

Concept for specialization of template type

Open geoffthemedio opened this issue 2 years ago • 0 comments

Channel

"C++Weekly"

Topics

How (best) to write a concept that checks if a type is a specialization of a template type, optionally a partial specialization of that template type.

For example, I want to check if the type provided to a function void ProcessData(auto input) is a sorted container, because if the input is sorted, I can use a more optimized implementation. This is presumably similar to passing boost::container::ordered_unique_range when providing sorted data a boost::container::flat_set constructor.

There might be another way to check if a type provides a sorted range, but one option is to manually specify a few types that would provide sorted ranges. For example, I could require that the input be a specialization of std::set or std::multiset or boost::container::flat_set. Specifying all possible fully specialized types of std::set would be awkward, due to various options for comparisons or allocators, so I'd like it to be a somewhat generic test for any or partially specialized std::set.

But how should I construct such a test?

Googling brought me to https://stackoverflow.com/questions/71921797/c-concepts-checking-if-derived-from-a-templated-class-with-unknown-template-p

That has a simple solution like https://godbolt.org/z/EY3jvPG3s for template types with a single template parameter, but which doesn't handle multiple template parameters. Using a parameter pack works, though: https://godbolt.org/z/4fcvxervW

That also has a more complicated solution that permits testing for particular partial specializations, which I've tweaked here: https://godbolt.org/z/o98hdhdYj

This seems to work on MSVC trunk, GCC >= 10.2, but not Clang trunk.

Length

5-10 probably sufficient.

geoffthemedio avatar Jul 14 '23 09:07 geoffthemedio