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

时间:2019-06-23 17:27:02

标签: c++ c++17 glm stdmap stdany

我想让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;
}

1 个答案:

答案 0 :(得分:1)

当我们询问“是否可以复制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标准库中似乎是一个错误。