c++ - 为什么 std::make_pair 不返回一对?或者是吗?

标签 c++ c++11 std-pair static-assert

我的内部完整性检查失败,所以我在 Stackoverflow 上重新运行它。

以下代码:

#include <iostream>
#include <typeinfo>
#include <utility>

int main()
{
    constexpr auto pair_of_ints = std::make_pair(1, 2);
    std::cerr << typeid(pair_of_ints).name();
    //static_assert(std::is_same<decltype(pair_of_ints), std::pair<int, int>>::value, "WTF");
}

std::__1::pair<int, int> 生成损坏的符号名称在我的系统上(XCode Clang 8.x)。

如果我随后启用 static_assert , 它失败。我不知道为什么。 我怎样才能使这项工作?我有一个函数根据传递给它的参数返回一对或元组,并想验证它是否在正确的情况下实际返回一对或元组。

最佳答案

您将 pair_of_ints 声明为 constexpr,这意味着 const:

[dcl.constexpr]#9

A constexpr specifier used in an object declaration declares the object as const.

所以pair_of_ints的类型其实是:

const std::pair<int, int>

typeid 忽略 cv-qualifiers,这就是为什么这个信息不会出现在名称中的原因:

[expr.typeid]#5

If the type of the expression or type-id is a cv-qualified type, the result of the typeid expression refers to a std::type_info object representing the cv-unqualified type.

您可以针对 const 限定类型进行测试,或者使用 std::remove_const_t 删除 const 限定符:

static_assert(std::is_same<decltype(pair_of_ints), 
                           const std::pair<int, int>>::value);
static_assert(std::is_same<std::remove_const_t<decltype(pair_of_ints)>, 
                           std::pair<int, int>>::value);

关于c++ - 为什么 std::make_pair 不返回一对?或者是吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499771/

相关文章:

c++ - 如何模拟 Google Test 中公共(public)方法正在使用的类中的私有(private)方法?

c++ - 二维世界速度到二维局部速度

c++ - 在 C++11 上下文中使用 std::optional

c++ - 基于对 vector 中第一个元素的降序排序没有给出期望的结果

c++ - 如何检查编译后的代码是否使用了 SSE 和 AVX 指令?

c++ - 在整数上声明两个指针(VS2012)

c++ - 多个可变参数模板函数

multithreading - 如何在多线程 gtkmm 应用程序中对抗 "Fatal IO error 11 (Resource temporarily unavailable) on X server"?

C++ 错误处理 - 使用 std::pair 或 std::tuple 返回错误代码和函数返回的缺点

c++ - 在集合中添加对