In C++ 17, there is a very useful alias template for metaprogramming that can be used to simplify use of SFINAE. The void_t
is a meta-function that is used to map any types ( or types) to type void
. In this post, we explain what is void_t, how you can use it in different examples.
Table of Contents
What is alias template void_t in C++ 17?
The void_t
is an alias template which is introduced with C++17, it is defined in <type_traits>
header and it is a metafunction that is used to map any types (or a sequence of any types) to type void
. The main purpose of void_t
is to make easy writing of type traits. It is used to solve SFINAE (Substitution Failure Is Not An Error) prior to concepts of C++20 standard. SFINAE rule says that If the deduced type or explicitly specified type for the template parameter fails, the specialization is discarded from the overload set instead of causing an error in compilation.
Since C++17, the std::void_t is defined as below.
Now, let’s see how we can use it in template definitions.
How to use alias template void_t to check a typename in a template?
We can use void_t
to if a class has a certain typename using at compile time, here we check if it has ‘type’ typename.
here is a full example about this, here we check ‘typeB
‘ typename if it has or not.
and the output will be as follows.
How to use alias template void_t to check a member in a template?
We can use void_t
to check if there is a member in a template, i.e. we can check if it has ‘varB’ member or not, as given below.
and the output will be as follows.
How to use alias template void_t to check if a class has a function name?
We can use void_t
to check if a class has a method. Here is an example that checks if myfB()
function exists in that class.
Here is a full example.
and the output will be as follows.
How to use alias template void_t to check whether a class is iterable?
We can use void_t
to check whether a class is iterable or not. Here is a simple example.
Here is a full example.
and the output will be as follows.
As you see, interestingly the void_t
is very useful to simplify use of SFINAE for metaprogramming.
For more details about this feature in C++17 standard, please see these papers; N3911
C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs.
There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.