简体   繁体   English

奇怪的运算符?:使用decltype

[英]Strange operator ?: usage with decltype

I am reading a book, that explains C++ traits and there is an example from C++ type_traits header with a strange ?: usage, here is the quote from the corresponding /usr/include/c++/... file: 我正在读一本解释C ++特性的书,并且有一个C ++ type_traits标题的例子有一个奇怪的?:用法,这里是相应的/ 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);

Setting aside the purpose of the given declaration, the ?: operator usage puzzles me in this code. 抛开给定声明的目的, ?:运算符用法使我在这段代码中困惑。 If the first operand is true , then std::declval<_Tp>() will always be chosen as result of the evaluation. 如果第一个操作数为true ,则将始终选择std::declval<_Tp>()作为评估结果。 How does that declval operand selection actually works? 这个declval操作数选择实际上是如何工作的?

Edit: originally read in Nicolai M. Josuttis's "The C++ Standard Library: A Tutorial and Reference, 2nd ed.", p.125. 编辑:最初阅读Nicolai M. Josuttis的“The C ++ Standard Library:A Tutorial and Reference,2nd ed。”,第125页。 But there it is given in a slightly simplified form as compared to what my GCC header files has. 但是与我的GCC头文件相比,它以略微简化的形式给出。

In the expression true ? std::declval<_Tp>() : std::declval<_Up>() 在表达式中是true ? std::declval<_Tp>() : std::declval<_Up>() true ? std::declval<_Tp>() : std::declval<_Up>() the first alternative is always selected, but the whole expression must be a valid expression. true ? std::declval<_Tp>() : std::declval<_Up>()始终选择第一个选项,但整个表达式必须是有效表达式。 So std::declval<_Up>() must be valid and that means _Up must be a callable that accepts zero arguments. 所以std::declval<_Up>()必须是有效的,这意味着_Up必须是一个接受零参数的可调用对象。 Beside that, _Tp() and _Up() must return the same type (or one of the types must be implicitly convertible to another), otherwise ternary iterator would not be able to select return value. 除此之外, _Tp()_Up()必须返回相同的类型(或者其中一个类型必须可以隐式转换为另一个),否则三元迭代器将无法选择返回值。

This technique is called SFINAE (substitution failure is not an error). 这种技术称为SFINAE(替换失败不是错误)。 The idea is that if template instantiation fails, then it is not an error, and this template is just ignored and compiler searches for another one. 我们的想法是,如果模板实例化失败,那么它就不是错误,只是忽略了这个模板,编译器会搜索另一个模板。

The idea here is that ?: requires that the second and third operand has the same type, or one type is convertible to the other. 这里的想法是?:要求第二个和第三个操作数具有相同的类型,或者一个类型可以转换为另一个。

Otherwise the instantiation of the function will fail, and some other overload is selected. 否则,函数的实例化将失败,并选择一些其他重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM