Beautiful code #2
Beautiful code #2 explanation
In the main function when we create an object to the class
string_input and pass arguments to call the range constructor that is declared inside the
template it checks for the type of the variable we are going to iterate. And for the passed type if the specific encoding class returns a boolean value of
true then the constructor is executed. In our example the constructor is called only when we need to iterate the
In the above code we pass
int as a default type to the CharTT. But it does not matter since in the
char and it overides the default value.
The above line of code is where the type is checked by the
std::enable_if_t function and for the specific
Encoding class if the
true and by default for the
default_encoding for the type
char it returns
_require_secondary_char_type holds the type
char when SFINAI (Substitution Failure Is Not An Error) function
char because the condition is met and substitution haven’t failed in our case.
CharTT holds the value char ( by default this is int) and the range constructor is executed.
Now let’t do a simple experiment. What will happen if we pass
int as a type to the range constructor? The default behaviour is the constructor must not be executed and let’s check that.
Consider the below code:
The only change in the above code is in the
main() function. I passed in
int to the template. You will get the below substitution failure.
This is my 2nd beautiful code in C++ post:) Hope you enjoyed it.
You will also like — More Articles
https://fluentprogrammer.com/beautiful-code-1-using-define-templates-r-value-reference/ https://fluentprogrammer.com/beautiful-code-3-no_unique_address_cpp_20-feature/ https://fluentprogrammer.com/beautiful-code-4-any_of-none_of-all_of/ https://fluentprogrammer.com/beautiful-code-5-for_each-optional/ https://fluentprogrammer.com/beautiful-code-6-copy_if-remove_copy_if-copy-back_inserter/