simplify the implementation of from_toml

This commit is contained in:
ToruNiina
2018-05-05 11:59:34 +09:00
parent 9555817901
commit 433636a06f
2 changed files with 22 additions and 55 deletions

View File

@@ -170,3 +170,22 @@ BOOST_AUTO_TEST_CASE(test_from_toml_tie)
BOOST_CHECK_EQUAL(ut["val4"].cast<toml::value_t::String >(), "piyo");
}
BOOST_AUTO_TEST_CASE(test_from_toml_tuple)
{
toml::Array a;
a.emplace_back(2);
a.emplace_back(7);
a.emplace_back(1);
a.emplace_back(8);
a.emplace_back(2);
toml::value v(a);
std::tuple<int, int, int, int, int> t;
toml::from_toml(t, v);
BOOST_CHECK_EQUAL(std::get<0>(t), 2);
BOOST_CHECK_EQUAL(std::get<1>(t), 7);
BOOST_CHECK_EQUAL(std::get<2>(t), 1);
BOOST_CHECK_EQUAL(std::get<3>(t), 8);
BOOST_CHECK_EQUAL(std::get<4>(t), 2);
}

View File

@@ -1,66 +1,14 @@
#ifndef TOML11_FROM_TOML
#define TOML11_FROM_TOML
#include "value.hpp"
#include "get.hpp"
namespace toml
{
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT != toml::value_t::Unknown &&
vT != value_t::Empty), std::nullptr_t>::type = nullptr>
template<typename T>
void from_toml(T& x, const toml::value& v)
{
if(v.type() != vT)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not arguemnt type: ") + stringize(vT));
x = v.cast<vT>();
return;
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
(!toml::detail::is_map<T>::value) &&
toml::detail::is_container<T>::value, std::nullptr_t>::type = nullptr>
void from_toml(T& x, const toml::value& v)
{
// TODO the case of x is not dynamic container case
if(v.type() != value_t::Array)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not argument type: Array"));
const auto& ar = v.cast<value_t::Array>();
try
{
toml::resize(x, ar.size());
}
catch(std::invalid_argument& iv)
{
throw toml::type_error("toml::from_toml: static array size is not enough");
}
auto iter = x.begin();
for(const auto& val : ar)
{
typename T::value_type v;
from_toml(v, val);
*iter = std::move(v);
++iter;
}
return;
}
template<typename T, toml::value_t vT = toml::detail::check_type<T>(),
typename std::enable_if<(vT == toml::value_t::Unknown) &&
toml::detail::is_map<T>::value, std::nullptr_t>::type = nullptr>
void from_toml(T& x, const toml::value& v)
{
if(v.type() != value_t::Table)
throw type_error("from_toml: value type: " + stringize(v.type()) +
std::string(" is not argument type: Table"));
x.clear();
const auto& tb = v.cast<value_t::Table>();
for(const auto& kv : tb)
{
x.insert(kv);
}
x = toml::get<T>(v);
return;
}