【发布时间】:2021-02-11 13:25:32
【问题描述】:
我的用例:我想构建一个常量内容和大小在编译时声明的 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' 失败。现场示例here。
似乎我假设std::pair 中的参数包作为模板参数应该创建一个类型为std::pair 的参数包是错误的。我如何让它工作,或者甚至可以让它按照我想要的方式工作?
【问题讨论】:
-
不是问题,但
std::pair<KeyType, Values>&&没有进行转发引用。只有在需要推导整个类型时才会创建转发引用,即:template <typename T> void foo(T&& fr)。
标签: c++ c++14 variadic-templates