c++ - 可变数量的 std::pair 元素的参数包扩展无法按预期工作
问题描述
我的用例:我想构建一个 constexpr 映射,其中包含在编译时声明的常量内容和大小。我正在使用 C++ 14。这是我目前对该容器的基本方法:
template <typename KeyType, typename ValueType, size_t size>
struct ConstantMap
{
using PairType = std::pair<KeyType, ValueType>;
using StorageType = std::array<PairType, size>;
const StorageType storage;
constexpr ValueType at (const KeyType& key) const
{
const auto it = std::find_if (storage.begin(), storage.end(), [&key] (const auto& v) { return v.first == key; });
if (it != storage.end())
return it.second;
throw std::range_error ("ConstantMap: Key not found");
}
constexpr ValueType operator[] (const KeyType& key) const { return at (key); }
};
有效的方法是像这样初始化它:
constexpr std::array<std::pair<int, int>, 2> values =
{{
{ 1, 2 },
{ 3, 4 }
}};
constexpr ConstantMap<int, int, 2> myMap {{ values }};
我想通过一个makeConstantMap
函数来简化这一点,该函数采用一对参数包并返回具有正确大小和键/值类型的映射,如下所示:
constexpr auto myMap = makeConstantMap<int, int> ({ 1, 2 }, { 3, 4 });
我的做法是
template <typename KeyType, typename ValueType, typename... Values>
constexpr ConstantMap<KeyType, ValueType, sizeof...(Values)> makeConstantMap (std::pair<KeyType, Values>&&... pairs)
{
return {{ std::forward<std::pair<KeyType, Values>> (pairs)... }};
}
哪个失败了candidate template ignored: substitution failure [with KeyType = int, ValueType = int]: deduced incomplete pack <(no value), (no value)> for template parameter 'Values'
。现场示例在这里。
似乎我假设一个参数包作为模板参数std::pair
应该创建一个类型为的参数包std::pair
是错误的。我如何让它工作,或者甚至有可能让它按照我想要的方式工作?
解决方案
也许通过旧的 C 样式数组?
template <typename KT, typename VT, std::size_t Dim, std::size_t ... Is>
constexpr auto mcp_helper (std::pair<KT, VT> const (& arr)[Dim],
std::index_sequence<Is...>)
{ return ConstantMap<KT, VT, Dim>{{ arr[Is]... }}; }
template <typename KT, typename VT, std::size_t Dim>
constexpr auto makeConstantMap (std::pair<KT, VT> const (& arr)[Dim])
{ return mcp_helper<KT, VT>(arr, std::make_index_sequence<Dim>{}); }
// ...
auto x = makeConstantMap<int, int>({{1, 2}, {3, 4}});
推荐阅读
- powershell - SharePoint PnP PowerShell - 从选项字段中获取选项
- python - 打开新标签时如何为浏览器计时
- python-2.7 - 在 matplotlib 中减去两个图
- javascript - 如何使用 JavaScript 验证注册和登录表单
- php - 我想使用日期和余额列总和而不是日期之间获取余额列数据的总和,按mysql中的customer_id分组
- html - 如何让 YouTube 自动播放为网站工作?
- python - 检查字符串是否可以使用提供的列表中的单词拆分成句子
- node.js - 在多个帐户之间切换时 Gdrive API V3 出现 403 错误
- python - 如何允许 ODBC 与 VS 2017 MSSQL Express 实例
- python - Python-'ValueError:将带有字符串的列表转换为整数时,int()的无效文字(以10为底)