[Intermediate] — The gap C++ feels most acutely on the web, and the workarounds that exist because the language has no reflection.
Why this is a whole note
In Go you write a struct tag. In Rust you write #[derive(Serialize)]. In Java, Jackson reads annotations at runtime. All three turn a type into JSON with one line, because the language can inspect a type’s fields — by reflection or by macro.
C++ has neither. There is no runtime reflection, and no stable macro system that can enumerate a struct’s members. So every field-to-JSON mapping is written by hand, or generated by a preprocessor trick.
This is the single biggest ergonomic gap between C++ and every other stack in frameworks/, and it’s felt on every endpoint.
nlohmann/json
The most pleasant option, and the usual default:
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json j;
j["id"] = 42;
j["email"] = "k@example.com";
j["tags"] = {"a", "b"};
std::string s = j.dump();
json parsed = json::parse(body); // THROWS on malformed input
int id = parsed.at("id").get<int>(); // .at() throws if missing; [] does notADL_SERIALIZER / the macro gets you struct conversion:
struct User {
int64_t id;
std::string email;
std::optional<std::string> name;
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(User, id, email, name)
json j = user; // now works
User u = j.get<User>();That macro is as close as C++ gets to #[derive(Serialize)] — and note you still list every field by name, twice if the struct changes. Add a field, forget the macro, and it silently doesn’t serialise. There’s no compiler check.
Parsing untrusted input safely:
json parsed = json::parse(body, nullptr, /*allow_exceptions=*/false);
if (parsed.is_discarded()) { return respond(400, "invalid json"); }
if (!parsed.contains("email") || !parsed["email"].is_string()) {
return respond(400, "email required");
}Three things that bite:
operator[]on a missing key default-constructs it (on a non-const object), like `std::map`. Use.at()or.contains()for lookups.get<int>()throws if the type doesn’t match. Wrap or useallow_exceptions=false- Deep nesting is a DoS vector —
json::parserecurses. Cap input size and depth
nlohmann is not the fastest. For hot paths, simdjson parses at gigabytes per second (and is read-only), or RapidJSON for a balance. Boost.JSON is a good middle option with allocator control.
The reflection situation
C++26 gets static reflection (P2996). It will let a library enumerate members at compile time and generate serialisation without macros or codegen:
// C++26, roughly — not usable yet
template <typename T>
json serialise(const T &obj) {
json j;
template for (constexpr auto member : std::meta::nonstatic_data_members_of(^T)) {
j[std::meta::identifier_of(member)] = obj.[:member:];
}
return j;
}This closes the gap properly. It is not usable today — compiler support is experimental and the standard isn’t finalised.
Until then, the options are:
1. Macros listing every field — nlohmann’s approach. Simple, and it duplicates the field list.
2. Boost.Describe — a macro that registers metadata, which other libraries then consume generically:
struct User { int64_t id; std::string email; };
BOOST_DESCRIBE_STRUCT(User, (), (id, email))
// now generic algorithms can enumerate members3. Code generation — a build step reading a schema or your headers and emitting the mapping. Protobuf, Cap’n Proto, and oat++‘s DTO system all do this. It’s the most robust and it adds a build dependency.
4. Don’t use JSON. For service-to-service traffic, Protobuf + gRPC sidesteps the whole problem: you define the message once in a .proto, and protoc generates C++ types with serialisation. Given how weak the JSON story is, gRPC is a genuinely more attractive option in C++ than it is elsewhere.
Validation
There’s no Pydantic, no validator tags, no Bean Validation. You write it:
struct CreateUser {
std::string email;
int age;
static std::expected<CreateUser, std::string> from_json(const json &j) {
CreateUser u;
if (!j.contains("email") || !j["email"].is_string())
return std::unexpected("email must be a string");
u.email = j["email"];
if (u.email.find('@') == std::string::npos)
return std::unexpected("email is invalid");
if (!j.contains("age") || !j["age"].is_number_integer())
return std::unexpected("age must be an integer");
u.age = j["age"];
if (u.age < 0 || u.age > 130)
return std::unexpected("age out of range");
return u;
}
};Verbose, and it has one real virtue: a static factory returning std::expected means an invalid CreateUser cannot be constructed. Make the constructor private and the type itself carries the guarantee — the C++ version of parse-don’t-validate.
That’s worth doing deliberately. The alternative — a plain struct filled in by the parser, validated somewhere later, maybe — is how validation gets skipped on the endpoint nobody reviewed.
std::expected is C++23. Before it, tl::expected or a std::variant<T, Error>. → Exceptions and Error Handling
Strings and zero-copy
void handle(std::string_view body); // no copy, no allocationstd::string_view and std::span are ideal for request parsing — a pointer and a length into the buffer that already exists. That’s the C++ answer to C’s array decay, and it removes a real cost on every request.
Two hazards:
std::string_view sv = get_body(); // DANGLING if that returns by valueA view doesn’t own. The buffer it points into must outlive it — and in an async handler, “outlive” means across suspension points, where the request buffer may have been recycled. Copy anything you keep past an await.
And a string_view is not NUL-terminated, so .data() cannot be passed to a C API expecting a C string. std::string(sv) when you need one.
Response building
auto resp = HttpResponse::newHttpJsonResponse(json); // Drogon
resp->setStatusCode(k201Created);
resp->addHeader("Location", "/users/" + std::to_string(id));For anything large, stream rather than buffer:
auto resp = HttpResponse::newStreamResponse(
[file = std::move(file)](char *buf, std::size_t len) mutable -> std::size_t {
return file.read(buf, len); // called repeatedly; constant memory
},
"export.csv", CT_TEXT_PLAIN);Building a 4GB response in a std::string will OOM. The streaming callback keeps memory constant, and it’s the same requirement as every other stack here.
Compression and content negotiation
drogon::app().enableGzip(true).enableBrotli(true);Frameworks handle this; Beast doesn’t. If you’re on Beast you implement Accept-Encoding parsing and compression yourself, which is another few hundred lines the other stacks give you free.
The summary
C++‘s web weakness is not performance — it’s the absence of reflection. Every other stack turns a type into JSON with one line; C++ makes you list the fields, or generate the code, or adopt Protobuf.
C++26 reflection fixes this properly. Until then: nlohmann for ergonomics, simdjson for speed,
std::expectedfactories for validation, and seriously consider gRPC for service-to-service traffic.
This is the concrete reason a CRUD-shaped service is more work in C++ than in Go or Rust — not the memory management, which RAII handles, but the sheer volume of hand-written mapping code. → When to Choose C++
Related
- Drogon and the Landscape — where responses get built
- C++: constexpr — type traits, and the reflection that isn’t there yet
- C++: Exceptions —
std::expected - APIs and REST — what you’re serialising
- C++ backends
Software engineering
Infrastructure & security
Computer science
Hardware & engineering