【发布时间】:2018-04-26 00:11:40
【问题描述】:
我正在尝试使用constexpr 和std::array 制作一个简单的编译时Bimap。
这似乎适用于第一个示例。 但是对于第二个示例,我有以下静态错误:
错误:static_assert 失败“3 == 3.3”
static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3"); //失败
这里是Wandbox 上提供的代码。应该使用Clang>=5.0.0 和GCC>=8.0.0 编译(除了上述错误)。
#include <utility>
#include <array>
#include <stdexcept>
#include <string_view>
#include <iostream>
template<class Key, class Value, std::size_t N>
struct MetaBimap {
using Item = std::pair<Key, Value>;
constexpr MetaBimap(const std::array<Item, N>& d)
: dictionnary{d}
{}
constexpr Value find_value_of_key(const Key& key, int range = N) const
{
if (range == 0)
throw std::out_of_range("Cannot find key");
return (dictionnary[range - 1].first == key)
? dictionnary[range - 1].second
: find_value_of_key(key, range - 1);
}
constexpr Key find_key_of_value(const Value& value, int range = N) const
{
if (range == 0)
throw std::out_of_range("Cannot find value");
return (dictionnary[range - 1].second == value)
? dictionnary[range - 1].first
: find_key_of_value(value, range - 1);
}
std::array<Item, N> dictionnary;
};
int main()
{
// first example
{
using namespace std::string_view_literals;
constexpr std::array<std::pair<std::string_view, int>, 3> meta_array {{
{ "one"sv, 1 },
{ "two"sv, 2 },
{ "three"sv, 3 }
}};
constexpr MetaBimap<std::string_view, int, 3> meta_dict = meta_array;
// OK on wandbox with Clang>=5.0.0 and GCC>=8.0.0 (though not working on my computer with Clang=5.0.0)
static_assert(meta_dict.find_value_of_key("one"sv) == 1, "one == 1");
static_assert(meta_dict.find_key_of_value(3) == "three"sv, "3 == three");
}
// second example
{
constexpr std::array<std::pair<float, int>, 3> meta_array {{
{ 1.1, 1 },
{ 2.2, 2 },
{ 3.3, 3 }
}};
constexpr MetaBimap<float, int, 3> meta_dict = meta_array;
static_assert(meta_dict.find_value_of_key(1.1) == 1, "1.1 == 1"); // OK
std::cout << meta_dict.find_key_of_value(3) << std::endl;
// static_assert(meta_dict.find_key_of_value(3) == 3.3, "3 == 3.3"); // fails
}
}
为什么会出现静态故障以及如何解决? 另外作为奖励,有什么方法可以简化 bimap 的构建?
【问题讨论】:
标签: c++ c++17 compile-time