std :: common

编程入门 行业动态 更新时间:2024-10-27 14:28:53
本文介绍了std :: common_type实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为了看看它是如何工作的,我看看 type_traits 。我不得不承认,我不真的明白它是如何工作的。这是:

Just to see how it worked, I looked at the libstdc++ implementation of std::common_type in the header type_traits. I have to admit that I don't really understand how it works. Here it is:

/// common_type template<typename... _Tp> struct common_type; template<typename _Tp> struct common_type<_Tp> { typedef _Tp type; }; template<typename _Tp, typename _Up> struct common_type<_Tp, _Up> { typedef decltype(true ? declval<_Tp>() : declval<_Up>()) type; }; template<typename _Tp, typename _Up, typename... _Vp> struct common_type<_Tp, _Up, _Vp...> { typedef typename common_type<typename common_type<_Tp, _Up>::type, _Vp...>::type type; };

我理解第一,第二和第四个声明是如何工作的。然而,我不能设法理解第三个声明的工作原理。

I understand well how the first, second and fourth declarations work. However, I can't manage to understand how the third declaration works. Could someone try to explain the mechanism used here?

推荐答案

首先, std :: declval< T> ;()生成 T 类型的r值。尝试对该值执行任何操作都将失败,因此它只能在未评估的上下文中使用。接下来,三元运算符将其类型推断为两个参数共同的最专用类型(如果没有这样的类型,则它失败)。所以,表达式的类型

First off, std::declval<T>() yields an r-value of type T. Trying to do anything with the value will fail so it can only be used in an unevaluated context. Next, the ternary operator deduces its type as most specialized type common to both arguments (if there is no such type, it fails). So, the type of the expression

true? declval<T0>(): declval<T1>()

code> T0 和 T1 。所有剩余的是将这个表达式转换为一个类型,并确保它不被评估。 decltype(expr)就是这样。显然,逻辑的牛肉的两个参数版本:其他人在那里处理角的情况(一个参数),并利用两个参数版本产生常见类型的任意类型。

is the most specialized common type of T0 and T1. All what remains is to turn this expression into a type and making sure that it isn't evaluated. decltype(expr) does just this. Clearly, the two argument version of the beef of the logic: the others are there to deal with the corner case (one argument) and to leverage the two argument version to yield the common type of arbitrary types.

更多推荐

std :: common

本文发布于:2023-11-05 16:01:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561273.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   common

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!