Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Overriding of custom type default values #1265

Merged
merged 1 commit into from
Jan 26, 2024

Conversation

jasonbeach
Copy link
Contributor

This is a simple PR that allows us to override defaults when decoding custom types. Consider:

struct Foo {
  int bar = 0;
};

namespace YAML {
template <>
struct convert<Foo> {
  static bool decode(const Node& node, Foo& f) {
    
    if (node["Bar"]) {
      f.bar = node["Bar"].as<int>();
    }
    // use the value that's already in f.bar
    return true;
  }
};

}  // namespace YAML

int main(int argc, char* argv[]) {
  auto node_good = YAML::Load("{Foo: {Bar: 3}}");
  auto node_bad = YAML::Load("{Foo: {}}");

  Foo f;
  f.bar = 99;
  f = node_good["Foo"].as<Foo>(f);
  fmt::print("bar: {} \n", f.bar);

  f.bar = 99;
  f = node_bad["Foo"].as<Foo>(f);
  fmt::print("bar: {} \n", f.bar);
}

Without the PR the output would be

bar: 3 
bar: 0 

result with this PR the output would be

$ ./build/Release/yaml_demo 
bar: 3 
bar: 99 

The big thing this enables diffing. i.e. if I have two yaml files, one that is a "base" that has all the my values and one that is a "diff" or a small subset that I may want to change, this makes overriding them much easier.

@jbeder jbeder merged commit 96f5c88 into jbeder:master Jan 26, 2024
33 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants