error: no template named 'adl_serializer'; #4110
Answered
by
gregmarr
mobergmann
asked this question in
Q&A
-
I have this code to serialize the lambda_strategy_t type. #include <variant>
#include <nlohmann/json.hpp>
namespace tef::optimizers
{
struct lambda_strategy
{
struct direct
{
double val;
};
struct mlu_threshold
{
double val;
};
lambda_strategy() = delete;
};
using lambda_strategy_t = std::variant<lambda_strategy::direct, lambda_strategy::mlu_threshold>;
namespace nlohmann
{
template <>
struct adl_serializer<lambda_strategy_t>
{
static void to_json(json &j, const lambda_strategy_t &strat)
{
j = nlohmann::json{};
j["direct"] = nullptr;
j["mlu_threshold"] = nullptr;
const auto direct = std::get_if<lambda_strategy::direct>(&strat);
const auto mlu_threshold = std::get_if<lambda_strategy::mlu_threshold>(&strat);
// either direct or mlu_threshold can be set in a variant
if (direct)
{
j["direct"] = direct->val;
j["mlu_threshold"] = nullptr;
}
if (mlu_threshold)
{
j["direct"] = nullptr;
j["mlu_threshold"] = mlu_threshold->val;
}
}
static void from_json(const json &j, lambda_strategy_t &strat)
{
const auto &direct = j.at("direct");
const auto &mlu_threshold = j.at("mlu_threshold");
// ensure, that either direct or mlu_threshold is set, because we are using a variant
if (direct == nullptr and mlu_threshold == nullptr)
{
throw std::logic_error("either 'direct' or 'mlu_threshold' has to be set");
}
else if (direct != nullptr and mlu_threshold != nullptr)
{
throw std::logic_error("only 'direct' or 'mlu_threshold' can be set");
}
else if (direct != nullptr)
{
strat = lambda_strategy::direct{direct};
}
else // if (mlu_threshold != nullptr)
{
strat = lambda_strategy::mlu_threshold{mlu_threshold};
}
}
};
} // namespace nlohmann
} // namespace tef::optimizers But I can't compile the project, I get the error:
I wan't to be able to use the |
Beta Was this translation helpful? Give feedback.
Answered by
gregmarr
Aug 30, 2023
Replies: 1 comment
-
The |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
mobergmann
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
adl_serializer
type is in::nlohmann
, you are trying to specialize it in::tef::optimizers::nlohmann
. You need to close your namespace first.