Skip to content

Instantly share code, notes, and snippets.

@flomnes
Last active March 25, 2025 10:04
Show Gist options
  • Save flomnes/13de4b2edaa92a7c0b4f48fb6139e8f4 to your computer and use it in GitHub Desktop.
Save flomnes/13de4b2edaa92a7c0b4f48fb6139e8f4 to your computer and use it in GitHub Desktop.
Enforce order of builder
class SystemBuilder
{
private:
class SystemBuilderConnections
{
public:
SystemBuilderConnections(SystemBuilder& parent):
parent(parent)
{
}
SystemBuilderConnections& withConnections(int y)
{
return *this;
}
void build()
{
}
private:
SystemBuilder& parent;
};
SystemBuilderConnections sbc;
public:
SystemBuilder():
sbc(*this)
{
}
SystemBuilderConnections& withComponents(int x)
{
return sbc;
}
};
int main()
{
SystemBuilder builder;
builder.withComponents(1).withConnections(2).build();
// connect.cc:32:13: error: ‘class SystemBuilder’ has no member named ‘withConnections’
// builder.withConnections(2).withComponents(1).build();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment