Skip to content

Commit

Permalink
Default keys for smart pointers.
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinH committed Jul 18, 2023
1 parent 3301293 commit de56743
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
10 changes: 8 additions & 2 deletions include/tao/json/contrib/traits.hpp
Expand Up @@ -116,12 +116,18 @@ namespace tao::json
template< typename T >
struct traits< std::shared_ptr< T > >
: shared_ptr_traits< T >
{};
{
template< template< typename... > class Traits >
using default_key = typename Traits< T >::template default_key< Traits >;
};

template< typename T >
struct traits< std::unique_ptr< T > >
: unique_ptr_traits< T >
{};
{
template< template< typename... > class Traits >
using default_key = typename Traits< T >::template default_key< Traits >;
};

} // namespace tao::json

Expand Down
35 changes: 35 additions & 0 deletions src/test/json/contrib_traits.cpp
Expand Up @@ -2,6 +2,8 @@
// Please see LICENSE for license or visit https://github.com/taocpp/json/

#include <limits>
#include <memory>
#include <string>

#include "test.hpp"
#include "test_events.hpp"
Expand Down Expand Up @@ -101,6 +103,38 @@ namespace tao::json
TEST_ASSERT( n != v );
}

struct default_type
: std::string
{
using std::string::string;
};

template<>
struct traits< default_type >
: traits< std::string >
{
TAO_JSON_DEFAULT_KEY( "default_key" );
};

void test_default()
{
const default_type a = "a";
const value v1 = { a };
TEST_ASSERT( v1.get_object().size() == 1 );
TEST_ASSERT( v1.get_object().begin()->first == "default_key" );
TEST_ASSERT( v1.get_object().begin()->second == "a" );
const auto b = std::make_unique< default_type >( "b" );
const value v2 = { b };
TEST_ASSERT( v2.get_object().size() == 1 );
TEST_ASSERT( v2.get_object().begin()->first == "default_key" );
TEST_ASSERT( v2.get_object().begin()->second == "b" );
const auto c = std::make_shared< default_type >( "c" );
const value v3 = { c };
TEST_ASSERT( v3.get_object().size() == 1 );
TEST_ASSERT( v3.get_object().begin()->first == "default_key" );
TEST_ASSERT( v3.get_object().begin()->second == "c" );
}

void test_deque()
{
const std::deque< std::uint64_t > f = { 1, 2, 3, 4 };
Expand Down Expand Up @@ -284,6 +318,7 @@ namespace tao::json

test_shared();
test_unique();
test_default();

test_deque();
test_list();
Expand Down

0 comments on commit de56743

Please sign in to comment.