我的内部完整性检查失败,所以我在 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
:
A
constexpr
specifier used in an object declaration declares the object asconst
.
所以pair_of_ints
的类型其实是:
const std::pair<int, int>
typeid
忽略 cv-qualifiers,这就是为什么这个信息不会出现在名称中的原因:
If the type of the expression or type-id is a cv-qualified type, the result of the
typeid
expression refers to astd::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/