簡體   English   中英

C++ 變體包含自身的 map

[英]C++ variant containing a map of itself

我希望能夠創建一個包含std::map<std::string, MyVariant>作為其案例之一的變體。 理想的情況是能夠寫出類似的東西

using MyVariant = std::variant<int, std::string, std::map<std::string, MyVariant>>;

但這需要前向聲明。

我知道以前曾問過類似的問題,例如herehere ,但這些問題主要集中在std::vector的情況下,並且由於 C++17 std::vector允許使用不完整類型,而std::map沒有。

特別是,我想知道這個答案中的定點組合器解決方案是否適用於這種情況? 從該答案改編代碼:

#include <map>
#include <string>
#include <variant>

// non-recursive definition
template<typename T>
using VariantImpl = std::variant<int, std::string, std::map<std::string, T>>;

// fixed-point combinator
template<template<typename> typename K>
struct FixCombinator : K<FixCombinator<K>>
{
    using K<FixCombinator>::K;
};

using MyVariant = FixCombinator<VariantImpl>;

但是,如果有另一種方法可以做到這一點,我也會對此感興趣。

這是不可能的(至少通過標准保證),因為std::variant要求使用的類型是完整的,而std::map要求鍵和值類型在實例化時是完整的類型。 但是只有在實例化之后,您的構造才會完成。

唯一允許這種遞歸構造(至少在某種程度上)的標准容器是std::vectorstd::liststd::forward_list

如果您想使用std::map並為其提供標准保證,則需要在某個時候添加一級間接。

暫無
暫無

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

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