代码之家  ›  专栏  ›  技术社区  ›  schorsch312

常量映射及其大小

  •  0
  • schorsch312  · 技术社区  · 6 年前

    我有一个 std::map 在运行时无法更改。因此,我标记了它 const 我无法标记它 constexpr ,因为具有非文字类型。

    我能推断出 size 这张地图的编译时间?

    #include <map>
    #include<string>
    
    int main (){
        const std::map <int, std::string> my_map { 
          { 42, "foo" }, 
          { 3, "bar" } 
        };
    
        constexpr auto items = my_map.size();
        return items;
    }
    

    This 未编译时出现以下错误:

    :10:20:错误:必须初始化constexpr变量“items” 通过一个恒定的表达式

    constexpr auto items = my_map.size();
    
                   ^       ~~~~~~~~~~~~~
    

    :10:35:注意:非constexpr函数“size”不能用于 不变的表达

    constexpr auto items = my_map.size();
    
    0 回复  |  直到 6 年前
        1
  •  3
  •   Equod    6 年前

    不幸的是,不能在constexpt上下文中使用std::map和std::string。如果可能,考虑切换到array and string_视图:

    int main() {
      constexpr std::array my_map{
          std::pair<int, std::string_view>{ 42, "foo" },
          std::pair<int, std::string_view>{ 3, "bar" }
      };
      constexpr auto items = my_map.size();
      return items;
    }
    

    然后使用constexpr-std算法

        2
  •  2
  •   NathanOliver    6 年前

    我能推断出 size 这张地图的编译时间?

    没有,自从 my_map 不是编译时常量,不能在编译时使用。

    该标准不提供编译时映射,但应该有库,或者如果您真的需要,可以自己创建库。

        3
  •  0
  •   Mestkon    6 年前

    如果您通过模板函数初始化地图,这是可能的

    template<class... Args>
    std::pair<std::integral_constant<std::size_t, sizeof...(Args)>, std::map<int, std::string>>
    make_map(Args&& ...args)
    {
        return {{}, std::map<int, std::string>({std::forward<Args>(args)...})};
    }
    
    int main() {
        const auto& p = make_map(
             std::make_pair( 42, std::string("foo") ), 
             std::make_pair( 3, std::string("bar") ) 
        );
    
        constexpr std::size_t size = std::decay_t<decltype(p.first)>::value;
        const auto& my_map = p.second;
        //or const auto my_map = std::move(p.second);
    }
    
    推荐文章