Add util::at helper

This commit is contained in:
Nikita Lisitsa 2023-08-06 12:55:31 +03:00
parent dd12ad9477
commit 128abc453e

View file

@ -0,0 +1,53 @@
#pragma once
#include <psemek/util/exception.hpp>
#include <psemek/util/to_string.hpp>
#include <vector>
namespace psemek::util
{
struct key_error_base
: exception
{
using exception::exception;
};
template <typename Key>
struct key_error
: key_error_base
{
key_error(Key const & key, boost::stacktrace::stacktrace stacktrace = {})
: key_error_base(util::to_string("no such key: ", key), std::move(stacktrace))
, key_(key)
{}
Key const & key() const
{
return key_;
}
private:
Key key_;
};
template <typename Container, typename Key>
auto & at(Container && container, Key const & key)
{
if (auto it = container.find(key); it != container.end())
return it->second;
throw key_error<Key>(key);
}
template <typename T, typename Key>
auto & at(std::vector<T> && container, Key const & key)
{
if (key < container.size())
return container[key];
throw key_error<Key>(key);
}
}