提问者:小点点

常量映射及其大小


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

我能在编译时推导出这个映射的大小吗?

#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;
}

编译时不会出现错误:

用法:10:20:错误:constexpr变量“items”必须由常量表达式初始化

constexpr auto items = my_map.size();

               ^       ~~~~~~~~~~~~~

用法:10:35:注意:非ConstExpr函数“size”不能用于常量表达式

constexpr auto items = my_map.size();

共3个答案

匿名用户

我能在编译时推导出这个映射的大小吗?

不是。因为my_map不是编译时常量,所以不能在编译时使用它。

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

匿名用户

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

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算法

匿名用户

如果您通过模板函数初始化映射,则有可能

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);
}