簡體   English   中英

如果std :: addressof是&的可讀版本。 *&的可讀版本是什么?

[英]If std::addressof is a readable version of &. What is a readable version of *&?

*&x

使用c ++ 11,我們可以寫成

* std::addressof(x)

但是,該表達式是否更具可讀性?

constexpr uint64_t lil_endian = 0x65'6e'64'69'61'6e; 
    // a.k.a. Clockwise-Rotated Endian which allocates like
    // char[8] = { n,a,i,d,n,e,\0,\0 }

constexpr auto& arr = 
    reinterpret_cast<const std::array<char,8> &>
        (*std::addressof(lil_endian) );

int main()
{
    const auto str = std::string(arr.crbegin()+2, arr.crend() );

    std::cout << str << '\n'
              << str.size() << '\n' << '\n';
    for (const auto ch : str) {
        std::cout << ch << " : " << std::hex << (unsigned int) ch << '\n';
    }

}


endian
6

e : 65
n : 6e
d : 64
i : 69
a : 61
n : 6e

godbolt.org/g/9StHsE

wandbox.org/permlink/ZzQ38IlDficO5UOi

* std::addressof(x)

但是,該表達式是否更具可讀性?

x

維托里奧·羅密歐(Vittorio Romeo)為您提供第二個問題的答案。

第一個假設是錯誤的:“是&的可讀版本的addressof 。” 即使對象的類類型具有重載的operator & addressof也用於獲取對象的地址。

目前尚不清楚您要做什么以及為什么使用constexpr

但是您的代碼有幾個問題:

  • 常量表達式中不允許 reinterpret_cast

  • 不允許使用std::arrayuint64_t別名。

但是,您可以通過在非constexpr上下文中使用const char*進行別名來解決這兩種情況。 因此,以下內容是合法的:

#include <iostream>

constexpr uint64_t lil_endian = 0x65'6e'64'69'61'6e; 

int main()
{
    auto arr = reinterpret_cast<const char*>(&lil_endian);
    for (size_t i = 0; i < sizeof(lil_endian); ++i) {
        std::cout << arr[i] << " : " << std::hex << (unsigned int) arr[i] << '\n';
    }

}

附帶地,對*&的需求也消失了。

演示

==編輯==

如果您只需要以通用方式掌握變量的大小 ,則只需在函數模板中使用sizeof 例如:

#include <cstdio>
#include <cstdint>

constexpr uint64_t lil_endian = 0x65'6e'64'69'61'6e; 
constexpr uint32_t lil_endian32 = 0x65'6e'64'69;

template<typename T>
void printIt(const T& it)
{
    auto arr = reinterpret_cast<const char*>(&it);
    for (size_t i = 0; i < sizeof(it); ++i) {
        putchar(arr[i]);
    }
}

int main()
{
    printIt(lil_endian);
    printIt(lil_endian32);
}

演示

暫無
暫無

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

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