簡體   English   中英

如何使用 std::tuple 等原始數組成員初始化元組<t[n]> ?</t[n]>

[英]How do I initialise a tuple with a raw array member such as std::tuple<T[N]>?

據我所知,標准std::tuple對其成員類型沒有任何限制,不允許原始 arrays。 所以這應該是一個有效的元組: std::tuple<char[3]> 但是,我似乎無法初始化它: Live example

char const hi[3] = "hi";
std::tuple<char[3]> tup; // fine
std::get<0>(tup)[0] = 'h'; // fine but not initialisation

std::tuple<char[3]> const tup1 = hi; // nope
std::tuple<char[3]> const tup2{hi}; // nope
std::tuple<char[3]> const tup3(hi); // nope
std::tuple<char[3]> const tup4 = std::make_tuple(hi); // nope
std::tuple<char[3]> const tup5 = std::make_tuple<char[3]>(hi); // nope

這會產生各種不同的錯誤消息。

所以我的問題是:

  • std::tuple<T[N]>應該合法嗎?
  • 如何正確初始化它?

注意:的,我完全知道我可以在元組中放置一個std::arraystd::string或任何其他容器。

大多數評論都涵蓋了問題所在,但是,我想補充一點,您不能這樣做,原因與您不能執行以下操作的原因相同:

    const char hi[3] = "hi";
    const char hi_copy[3] { hi }; // Compile time error. 

元組構造函數只是試圖結束上述初始化。 您可以執行以下操作:

    const char* hi = new char[3] {'h', 'i', '\0'};
    std::tuple<const char*> const tup2{ hi };

這顯然是一個丑陋的黑客,不應該使用。

您還應該記住,c-type arrays 的行為類似於指針,請考慮以下事項:

    const char hi[3] = "hi";        
    std::cout << "Second letter of hi var is " << *(hi + 1);

hi加一實際上會移動指針,取消引用指針指向的值將產生它的值。

In a nutshell: C and C++ are different languages, its just so happens to be that C++ has extremely good support for C. 它會在 99.9% 的時間里工作,你只是碰到了兼容性不完美的地方。

使用 std::array 而不是指針數組。 https://en.cppreference.com/w/cpp/container/array

暫無
暫無

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

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