13

What is the purpose of the class = void in the following code snippets?

template< class, class = void >
struct has_type_member : false_type { };

template< class T >
struct has_type_member<T, void_t<typename T::type>> : true_type { };
laike9m
  • 18,344
  • 20
  • 107
  • 140
msc
  • 33,420
  • 29
  • 119
  • 214

1 Answers1

14
template< class, class = void >
struct has_type_member : false_type { };

That's your default struct template, it asks for 2 template arguments but the second one is set to void as default, so this argument does not need to be specified explicitly, somewhat like a default function parameter.

Then :

template< class T >
struct has_type_member<T, void_t<typename T::type>> : true_type { };

Is a template specialization for your has_type_member struct, SFINAE will rule out this specialization if T::type doesn't exist (and thus, is invalid syntax), if it does exist it will pick this specialization otherwise.

The 2nd parameter is necessary to be used for template specialization, but we don't use it in our "fallback" struct so we just default to void.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122