Skip to content

feat: Allow decoding for types without default constructor - #1479

Open
SGSSGene wants to merge 1 commit into
jbeder:masterfrom
SGSSGene:feat/not-default-decoder
Open

feat: Allow decoding for types without default constructor#1479
SGSSGene wants to merge 1 commit into
jbeder:masterfrom
SGSSGene:feat/not-default-decoder

Conversation

@SGSSGene

@SGSSGene SGSSGene commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

This PR is inspired by #1010, but instead of creating a new customization point via decode_dispatcher it reuses convert by using convert<std::optional<T>> specialization for non-default constructible classes.

If cmake variable YAML_CPP_USE_OPTIONAL is set (automatically set if target is c++17 or above) this new feature is activated. It can be deactivated by setting YAML_CPP_USE_OPTIONAL to false to force old behavior if desired.

When decoding a type T, it will use convert<std::optional<T>> and forward to convert<T> if not available.
The signature requirements are as before but by using the additional std::optional it allows us to delay the construction of our type T.
Assume we have some type without default constructor:

class Vec3 {
  double x, y, z;
public:
  Vec3(double x, double y, double z} : x{x}, y{y}, z{z} {}
};

you could write

namespace YAML {
template<>
struct convert<std::optional<Vec3>> {
  static bool decode(const Node& node, std::optional<Vec3>& rhs) {
    if(!node.IsSequence() || node.size() != 3) {
      return false;
    }
    rhs.emplace(
        node[0].as<double>(),
        node[1].as<double>(),
        node[2].as<double>()
    );
    return true;
  }
};
}

To implement encoding for Vec3 one must still implement convert<Vec3> with the encode method.

Notes:
fixes #973 #993
alternative for PR #1010 and #1087

PR #1087 breaks API and relies on exception paths which I don't like, since this seems like normal control flow to me.

@SGSSGene
SGSSGene force-pushed the feat/not-default-decoder branch from 2897332 to 41be05a Compare August 10, 2026 09:27
@SGSSGene
SGSSGene requested a review from jbeder August 10, 2026 09:29
@SGSSGene
SGSSGene force-pushed the feat/not-default-decoder branch 4 times, most recently from 9522ee9 to d1f8ebc Compare August 10, 2026 10:46
@SGSSGene

SGSSGene commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator Author

Maybe it also enough to consider it as a fix for #506

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.

Better support for "default"

1 participant