左值和右值的C ++ std :: is_integral显示不同的结果

时间:2020-04-25 09:49:04

标签: c++ c++11 rvalue lvalue

我创建了一个类型验证器,以检查给定的参数是否为数字。

template<typename T>
struct is_numeric
    : std::integral_constant<
        bool,
        std::is_integral_v<T> || std::is_floating_point_v<T>
    > {};

template<typename T>
inline constexpr bool is_numeric_v = is_numeric<T>::value;

template<typename T>
constexpr bool is_numeric_tuple(T&& value)
{ return is_numeric_v<T>; }

// variadic template implementation is omitted

现在,问题在于

int i = 3;
is_numeric_tuple(3)  // returns true
is_numeric_tuple(i)  // returns false

如果我将std::remove_reference应用于is_numeric_tuple,两个结果都将是真实的。

这是否意味着type_traits的{​​{1}},is_integral等STL实现将给定类型强制为右值?

如果是,为什么?

更新

正如 geza 所述,我使用的is_floating_point库仅指定了一种类型本身,这意味着

type_traits

问题与左值或右值无关。

2 个答案:

答案 0 :(得分:1)

似乎您正在混淆价值类别和类型。这些是紧密相连的,但不尽相同。

type_traits需要一个 type 参数。在这里谈论右值没有意义,因为表达式具有值类别。

is_integral需要一个非引用类型来返回trueis_integral_v<int &&>(右值引用)仍返回false,因为它是引用类型。

在您的第一个示例(文字3)中,T将推导为int,因此is_numeric_tuple会返回true(原样非引用类型)。

在第二个示例中,T被推导为int &,因此它将返回false(因为它是引用类型)。

答案 1 :(得分:0)

这些类型特征旨在表示不同的类别。每种类型都属于these categories之一:

enter image description here

类型int&是引用类型,而不是整数类型。因此,is_integral返回false