簡體   English   中英

為什么std :: make_pair不返回一對? 還是呢?

[英]Why does std::make_pair not return a pair? Or does it?

我的內部健全性檢查失敗,因此我正在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");
}

在我的系統(XCode Clang 8.x)上為std::__1::pair<int, int>生成錯誤的符號名稱。

如果然后啟用static_assert ,它將失敗。 我不知道為什么。 我該如何進行這項工作? 我有一個函數,它根據傳遞給它的參數返回一個對或元組,並想驗證它是否在正確的情況下實際上返回了一個對或元組。

您將pair_of_ints聲明為constexpr ,這意味着const

[dcl.constexpr]#9

對象聲明中使用的constexpr說明符將該對象聲明為const

所以pair_of_ints的類型實際上是:

const std::pair<int, int>

typeid忽略cv限定詞,這就是為什么此信息未出現在名稱中的原因:

[expr.typeid]#5

如果表達式的類型或type-id是cv限定的類型,則typeid表達式的結果將引用表示cv不限定的類型的std::type_info對象。

您可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM