Add util::at helper
This commit is contained in:
parent
dd12ad9477
commit
128abc453e
1 changed files with 53 additions and 0 deletions
53
libs/util/include/psemek/util/at.hpp
Normal file
53
libs/util/include/psemek/util/at.hpp
Normal 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue