Strange statement ?: Use with decltype

I am reading a book that explains the features of C ++, and there is an example from the C ++ header of type_traits with strange usage ?: , Here is a quote from the corresponding file / usr / include / C ++ / ...:

 template<typename _Tp, typename _Up> static __success_type<typename decay<decltype (true ? std::declval<_Tp>() : std::declval<_Up>())>::type> _S_test(int); 

Overriding the purpose of this declaration, the use of the ?: Operator causes puzzles in this case. If the first operand is true , then std::declval<_Tp>() will always be selected as a result of the evaluation. How does this descriptive operand selection work?

Edit: originally read in Nicolae M. Josuttis "C ++ Standard Library: Tutorial and Reference, 2nd ed.", P. 125. But there it is given in a slightly simplified form compared to my GCC header files.

+5
source share
2 answers

In the expression true ? std::declval<_Tp>() : std::declval<_Up>() true ? std::declval<_Tp>() : std::declval<_Up>() first alternative is always selected, but the whole expression must be a valid expression. Therefore, std::declval<_Up>() must be valid, which means _Up must be callable, which takes null arguments. In addition, _Tp() and _Up() must return the same type (or one of the types must be implicitly converted to another), otherwise the ternary iterator will not be able to select the return value.

This method is called SFINAE (replacement failure is not an error). The idea is that if the template instance failed, then this is not an error, and this template is simply ignored, and the compiler is looking for another.

+10
source

The idea here is that ?: Requires the second and third operands to have the same type, or one type to be converted to another.

Otherwise, an instance of the function is created, and some other overload is selected.

+3
source

Source: https://habr.com/ru/post/1257607/


All Articles