Skip to content

Serializing std::variant causes stack overflow #1292

@untrioctium

Description

@untrioctium

This may be similar to #1261, but version 3.3.0, on my tested compilers, will stack overflow trying to serialize a variant instead of yelling at compile time that it doesn't know how to do it.

With this code:

#include "json.hpp"
#include <variant>
#include <iostream>

int main() {
	std::variant<int, float, std::string> t = 3.14159f;
	std::cout << nlohmann::json(t).dump() << std::endl;
}

MSVC 19.14.26430 will produce the cryptic and lengthy error C4717:

'nlohmann::detail::json_ref<nlohmann::basic_json<std::map,std::vector,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,bool,__int64,unsigned __int64,double,std::allocator,nlohmann::adl_serializer> >::json_ref<nlohmann::basic_json<std::map,std::vector,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,bool,__int64,unsigned __int64,double,std::allocator,nlohmann::adl_serializer> ><std::variant<int,float,std::basic_string<char,std::char_traits<char>,std::allocator<char> > > &>': recursive on all control paths, function will cause runtime stack overflow

And crash with a stack overflow when run. GCC 7.3.0 and Clang 6.0.0 will not produce a compile error, but will segfault. An earlier version of json I was working with, 3.1.2, instead complains that it's not sure how to serialize a std::variant on all previously tested compilers.

json.hpp:1545:5: error: static assertion failed: could not find to_json() method in T's namespace
     static_assert(sizeof(BasicJsonType) == 0,

I cannot even begin to claim to know what the resolution of this problem might even vaguely look like, but I hope this is helpful information. Hopefully I'm not just doing something horribly wrong.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions