我有一个std::map
,它在运行时无法更改。因此,我已将其标记为const
,因为它具有非文字类型,所以无法对其进行标记。{p}
我可以在编译时推断这张地图的constexpr
吗?
size
This不能编译并显示错误:
:10:20:错误:必须初始化constexpr变量“ items” 用一个常量表达式
#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:35:注意:非constexpr函数'size'不能用于 一个常数表达式
constexpr auto items = my_map.size(); ^ ~~~~~~~~~~~~~
答案 0 :(得分:3)
不幸的是,您不能在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算法
答案 1 :(得分:2)
我可以在编译时推断这张地图的
size
吗?
不。由于my_map
不是编译时间常数,因此您不能在编译时使用它。
该标准没有提供编译时间图,但是应该有一个库,否则,如果您确实需要它,可以自己制作。
答案 2 :(得分:0)
如果您通过模板函数初始化地图,则有可能
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);
}