转换后是右值还是左值

Is it an Rvalue or Lvalue After a Cast

此处的代码在类型转换后测试左值或右值:

#include <stdio.h>

template <typename T>
T const f1(T  const &t) {
  printf("T const \n");
  return t;
}
template <typename T>
T  f1(T  &t) {
  printf("T\n");
  return t;
}
struct KK {
  int a;
};

int main()
{
  KK kk;
  kk.a=0;

  int ii;
  f1(kk);
  f1((KK)kk);

  f1(ii);
  f1((int)ii);
 return 0;
}

在 gcc link 中,结果是这样的,表明右值在类型转换后产生:

T
T const 
T
T const 

但是在VC++2010中,只有当它是class类型时,这是表示右值的结果:

T
T const
T
T

这是编译器错误还是类型转换为 int 时的一些未定义行为?

来自 expr.cast(这适用于 C++11 及更高版本)

The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue. [ Note: If T is a non-class type that is cv-qualified, the cv-qualifiers are discarded when determining the type of the resulting prvalue; see Clause [expr]. — end note ]


对于 C++98:

The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is a reference type, otherwise the result is an rvalue. [ Note: if T is a non-class type that is cv-qualified, the cv-qualifiers are ignored when determining the type of the resulting rvalue; see 3.10. — end note ]

那么,gcc就对了


根据 mkaes 的评论,这似乎是 (可以说是有用的)MSVC 扩展