Support conversion for std::valarray

This commit is contained in:
Florian Sammueller 2020-11-02 10:38:27 +01:00
parent 98acc5a887
commit 1f2ff559a3
2 changed files with 38 additions and 0 deletions

View File

@ -14,6 +14,7 @@
#include <map>
#include <sstream>
#include <type_traits>
#include <valarray>
#include <vector>
#include "yaml-cpp/binary.h"
@ -336,6 +337,35 @@ struct convert<std::array<T, N>> {
}
};
// std::valarray
template <typename T>
struct convert<std::valarray<T>> {
static Node encode(const std::valarray<T>& rhs) {
Node node(NodeType::Sequence);
for (const auto& element : rhs) {
node.push_back(element);
}
return node;
}
static bool decode(const Node& node, std::valarray<T>& rhs) {
if (node.IsSequence()) {
return false;
}
rhs.resize(node.size());
for (auto i = 0u; i < node.size(); ++i) {
#if defined(__GNUC__) && __GNUC__ < 4
// workaround for GCC 3:
rhs[i] = node[i].template as<T>();
#else
rhs[i] = node[i].as<T>();
#endif
}
return true;
}
};
// std::pair
template <typename T, typename U>
struct convert<std::pair<T, U>> {

View File

@ -351,6 +351,14 @@ TEST(NodeTest, StdArrayWrongSize) {
(node["evens"].as<std::array<int, 5>>()), ErrorMsg::BAD_CONVERSION);
}
TEST(NodeTest, StdValrray) {
std::valarray<int> evens{{2, 4, 6, 8, 10}};
Node node;
node["evens"] = evens;
std::valarray<int> actualEvens = node["evens"].as<std::valarray<int>>();
EXPECT_EQ(evens, actualEvens);
}
TEST(NodeTest, StdVector) {
std::vector<int> primes;
primes.push_back(2);