glideapps / quicktype

Generate types and converters from JSON, Schema, and GraphQL
https://app.quicktype.io
Apache License 2.0
12.12k stars 1.06k forks source link

C++ Error : cannot convert from 'fromType' to 'std::optional<std::string> #2383

Open deandt100 opened 1 year ago

deandt100 commented 1 year ago

Hi,

I am getting the following compile error when optional properties are used alongside wstring (C++17)

Error

'return': cannot convert from 'fromType' to 'std::optional<std::string>'

Schema (from example on quicktype.io)

{
  "id": "http://json-schema.org/geo",
  "$schema": "http://json-schema.org/draft-06/schema#",
  "description": "A geographical coordinate",
  "type": "object",
  "properties": {
    "latitude": {
      "type": "number"
    },
    "longitude": {
      "type": "number"
    }
  }
}

Options used

quicktype schema.json -o testy.h --namespace quicktype  -s schema --lang c++ --wstring use-wstring --no-boost --include-location global-include --code-format with-struct  --hide-null-optional

Code :

#include <string>
#include <iostream>
#include <sstream>
#include "generated/testy.h"
#include "testy.h"

int main()
{
    quicktype::coordinate request;
    auto json = quicktype::wdump(static_cast<nlohmann::json>(request));
    std::wcout << json;
}

I believe this can be fixed by adding the following convert overloads to the generated Utf16_Utf8 class :

static std::optional<std::string> convert(tag<std::optional<std::wstring>>, tag< std::optional<std::string>>, std::optional<std::wstring> str) 
{
    return str.has_value() ? std::optional{ convert(tag<std::wstring>(), tag<std::string>(), str.value()) } : std::nullopt;
}

static std::optional<std::wstring> convert(tag<std::optional<std::string>>, tag< std::optional<std::wstring>>, std::optional<std::string> str) 
{
    return str.has_value() ? std::optional{ convert(tag<std::string>(), tag<std::wstring>(), str.value()) } : std::nullopt;
}