c++ - 带有对 type_info 的引用的 std::common_type

标签 c++ templates c++11

我很困惑:升级到 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& 案例会失败,但其他任何看似等效的类型都不会失败?

请看这里:https://godbolt.org/g/Ob4y0x

最佳答案

首先,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&>::typetype_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&>::typecommon_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/

相关文章:

c++ - QWebView中的登出功能

c++ - 构造函数失败后初始化 boost::asio 套接字

c++ - 使用枚举参数重载模板时出现 MSVC 编译器错误

c++ - 是否应该为类成员访问表达式中的依赖类/命名空间名称延迟名称查找?

c++ - add_lvalue_reference实现示例

c++ - 包扩展不在最后一个参数中的可变参数函数模板

c++ - 我在这段代码中要求一个数字,如果用户给的是一封信,我该怎么办?

c++ - 包括使用 cmake 的 antlr4 c++ 运行时

c++ - 将函数的返回 vector 分配给另一个 vector 时出现段错误

c++ - 模板 ID 与任何模板声明都不匹配