我很困惑:升级到 GCC 6 (RC1) 后,一些使用 std::common_type
的模板代码在失败之前有效。我尝试了clang,但也失败了......所以我一定做错了什么!
代码相当于:
#include <type_traits>
#include <typeinfo>
using namespace std;
// common_type of two const type_info& is ok (compiles ok)
common_type<const type_info&, const type_info&>::type func1();
// common_type of three type_info& is bad...(fails to compile)
common_type<const type_info&, const type_info&, const type_info&>::type func2();
// common_type of two const int& is ok
common_type<const int&, const int&>::type func3();
// common_type of three const int& is ok too!
common_type<const int&, const int&, const int&>::type func4();
具有 std::type_info const &
类型的三个参数的第二个 common_type
无法编译。 clang 神秘地建议我使用两个参数 std::common_type
,但这是在模板扩展中,我无法控制输入!
这似乎很奇怪:为什么带有 3 的 const type_info&
案例会失败,但其他任何看似等效的类型都不会失败?
最佳答案
首先,common_type_t<T1, T2>
是(大约)std::decay_t<decltype(true? std::declval<T1>() : std::declval<T2>())>
.它衰减类型 - 剥离引用,移除顶级 cv 限定,并进行数组到指针和函数到指针的转换。
所以,common_type<const type_info&, const type_info&>::type
是 type_info
.而func1
的声明似乎有效,但您在编写其定义时会遇到严重问题。
common_type_t<T1, T2, T3>
是 common_type_t<common_type_t<T1, T2>, T3>
, 所以 common_type<const type_info&, const type_info&, const type_info&>::type
是 common_type<type_info, const type_info&>::type
.
这会产生一个混合值类别的三元表达式,根据 [expr.cond] 中的规则,它将尝试生成一个临时的 type_info
超出所选操作数 - 因为 type_info
不起作用的复制构造函数被删除。
在 SFINAE 友好的实现中,这会导致 common_type<const type_info&, const type_info&, const type_info&>
没有成员(member)type
.如果您使用非 SFINAE 友好的实现,则会收到硬错误。
关于c++ - 带有对 type_info 的引用的 std::common_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36704684/