I use the following methods to write objects in json format:
#include <array>
#include <vector>
#include <jsoncpp/json/json.h>
//// Write json SFINAE
template <typename T>
struct has_write_json_method {
template <typename U>
static constexpr decltype(std::declval<U>().write_json(), bool()) test(int) { return true; };
template <typename U>
static constexpr bool test(...) { return false; }
static constexpr bool value = test<T>(int());
};
template <class T>
typename std::enable_if<has_write_json_method<T>::value, Json::Value>::type write_json(const T& object) { return object.write_json(); };
template <class T>
typename std::enable_if<!has_write_json_method<T>::value, Json::Value>::type write_json(const T& object);
//// Write json vector
template <class T>
Json::Value write_json(const std::vector<T>& object_v) {
Json::Value output;
for (int i = 0; i < object_v.size(); ++i) { output[i] = write_json<T>(object_v.at(i)); };
return output;
};
//// Write json array
template <class T, std::size_t N>
Json::Value write_json(const std::array<T, N>& object_v) {
Json::Value output;
for (int i = 0; i < object_v.size(); ++i) { output[i] = write_json<T>(object_v.at(i)); };
return output;
};
//// Write json basic
template <class T>
Json::Value write_json_basic(const T& object) {
Json::Value output;
output = object;
return output;
};
template<>
Json::Value write_json<Json::Value>(const Json::Value& object) { return write_json_basic(object); };
template<>
Json::Value write_json<double>(const double& object) { return write_json_basic(object); };
However, when I try to write a std::array of std::vector:
std::array<std::vector<double>, 4> foo_av;
Json::Value output = write_json(foo_av);
It doesn't compile in C++11:
undefined reference to `std::enable_if<!has_write_json_method<std::vector<double, std::allocator<double> > >::value, Json::Value>::type write_json<std::vector<double, std::allocator<double> > >(std::vector<double, std::allocator<double> > const&)'
Aucun commentaire:
Enregistrer un commentaire