繁体   English   中英

将std :: map与std :: any用作值类型

[英]Use std::map with std::any as value type

我想让Config类能够在字符串键中存储任何值。 为此,似乎std :: map适合。 不幸的是,这还没有编译。

看起来好像std::is_copy_constructible<std::tuple<const std::any&>>特征失败。 我该如何克服? 请在https://github.com/marchevskys/VisualEngine中找到源。

代码思路如下:

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <any>
#include <map>
//#include <glm/glm.hpp>

//using vec3d = glm::vec<3, double, glm::highp>;

class Config {
public:
   static Config* get() {
    static Config config;
    return &config;
    }

   enum class Option : int {
      ImGuiEnabled = 0x0,   // bool
      ShipPosition = 0x1    // glm::vec3
   };

   using cb_function = std::function<void(std::any)>;

   bool is_option_available(Option option) const { return m_config.at(option).has_value(); }
   std::any get_option(Option option) const { return m_config.at(option); }
   void set_option_value(Option option, const std::any& value) { m_config.insert_or_assign(option, value); }
private:
   Config() {/* m_config[Option::ShipPosition] = vec3d({ 0., 0., 0. }); */} 
   ~Config() = default;
   std::map<Option, std::any> m_config;
};

int main()
{
    Config::get()->set_option_value(Config::Option::ImGuiEnabled, false);
    bool isImGuiEnabled = std::any_cast<bool>(Config::get()->get_option(Config::Option::ImGuiEnabled));
    std::cout << std::boolalpha << "ImGuiEnabled ? " << isImGuiEnabled << std::endl;
}

该版本可在MS Visual Studio上编译,且版本早于9.1.0 g ++,但不会在g ++ 9.1.0上编译。

您可以通过以下方式得到相同的错误:

#include <type_traits>
#include <tuple>
#include <any>

int main()
{
  bool b = std::is_copy_constructible< std::tuple<const std::any&> >::value );
  (void)b;
}

当我们询问“是否可以复制std::tuple<const std::any&> ”时,就会触发奇怪的错误。

这最终会中断,因为要复制它最终会检查“可以复制std::tuple<const std::any&> ”作为中间步骤。

这是因为该中间步骤中的一个包括检查是否可以做出std::any const&从一个std::tuple<std::any const&> ,这反过来又询问是否可以复制一个std::tuple<std::any const&> ,其中询问是否可以使一个std::any const&从一个std::tuple<std::any const&>

所有这些似乎都是由映射中的代码触发的,该代码将第二个参数捆绑在std::tuple ,然后尝试用它来置换std::any 但是,它会尝试这两种构造std::any的论据,并与元组作为一个整体。

在GCC标准库中,这似乎是一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM