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

{..}没有类型,只能推断为initilizer_list<T>T(&)[N]

所以call必须是这样的:

makeConstantMap(std::pair<int, int>{ 1, 2 }, std::pair<int, int>{ 3, 4 });

可能的解决方法,有硬编码限制,如:

template <typename Key, typename Value>
struct MapMaker
{
constexpr ConstantMap<Key, Value, 0> operator()() const { return {}; }
constexpr ConstantMap<Key, Value, 1> operator()(std::pair<Key, value> p1) const {
return {{ std::array<std::pair<Key, value>, 1>{{p1}} }};
}
constexpr ConstantMap<Key, Value, 2> operator()(std::pair<Key, value> p1,
std::pair<Key, value> p2) const {
return {{ std::array<std::pair<Key, value>, 1>{{p1, p2}} }};
}
// ...
};

constexpr auto myMap = MapMaker<int, int>{}({ 1, 2 }, { 3, 4 });

最新更新