Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'typename Enable = void' mean?

Tags:

c++

templates

I found typename Enable = void is defined in the ProtoBuf,

template<typename T, typename Enable = void>
struct RefTypeTraits;

However, I cannot find the Enable is used in this header file, which confuse me. What does typename Enable = void mean in template?

like image 679
zangw Avatar asked Dec 25 '15 02:12

zangw


People also ask

What is the use of Typename?

" typename " is a keyword in the C++ programming language used when writing templates. It is used for specifying that a dependent name in a template definition or declaration is a type.

What is the difference between Typename and class?

There is no difference between using <typename T> OR <class T> ; i.e. it is a convention used by C++ programmers. I myself prefer <typename T> as it more clearly describes its use; i.e. defining a template with a specific type.

What is enable if?

The enable_if family of templates is a set of tools to allow a function template or a class template specialization to include or exclude itself from a set of matching functions or specializations based on properties of its template arguments.

What is template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.


2 Answers

It is to allow SFINAE with template specialization, as something like:

template <typename T>
struct RefTypeTraits<T, std::enable_if_t<some_condition<T>::value>>
{
    // ... specialization for T which respects condition
};

Since C++20, we can specialize with concepts to avoid this needed extra template parameter.

like image 106
Jarod42 Avatar answered Sep 28 '22 00:09

Jarod42


Your template just has two template parameters. The second one is called "Enabled" and it has the default type of "void". This is a trick to allow SFINAE later on.

like image 22
Vaughn Cato Avatar answered Sep 28 '22 02:09

Vaughn Cato