Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ require type alias exists in type

Is there a way to require that a given type has a type alias defined within it? For example, how could I write a concept to check that this would be valid where the concept checks that the type T has a type alias Bar?

template <typename T>
concept HasBarType = ????;

template <HasBarType T>
void foo() {
    [[maybe_unused]] T::Bar bar;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

template <typename T>
concept HasBarType = requires { typename T::Bar; };

This checks that T::Bar names a type. It can be a type alias in T, a nested class in T, a base class of T or the injected-class-name of T itself, though.

The typename keyword at the beginning makes this a type-requirement which has different semantics than the same line without typename or with additional braces instead.

With typename it requires T::Bar to name a type.

Without typename it is a simple-requirement which requires T::Bar to be a well-formed expression.

With additional braces, optionally followed by -> type-constraint it is a compound-requirement which requires the expression typename T::Bar to be well-formed and the result type of the expression to satisfy the specified type-constraint. (That’s impossible because typename T::Bar doesn’t have a valid form for an expression.)

You also need typename before T::Bar in the non-static data member, because T::Bar is dependent.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading