From 1b1be9e6b2149867c5de67a3dc62ed997f803334 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sun, 5 Nov 2017 13:00:35 +0100 Subject: [PATCH] KV tables - getOrCreate --- include/ebcl/HashTables.hh | 3 +++ include/ebcl/inline/HashTables.hh | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/include/ebcl/HashTables.hh b/include/ebcl/HashTables.hh index 4f8219f..1a894f5 100644 --- a/include/ebcl/HashTables.hh +++ b/include/ebcl/HashTables.hh @@ -99,6 +99,9 @@ class T_KeyValueTable ValueType const * get( KeyType const& k ) const; ValueType * get( KeyType const& k ); + template< typename... ArgTypes > + ValueType& getOrCreate( KeyType const& k , ArgTypes&&... args ); + ValueType& operator[] ( uint32_t index ); ValueType const& operator[] ( uint32_t index ) const; diff --git a/include/ebcl/inline/HashTables.hh b/include/ebcl/inline/HashTables.hh index ef72542..22dc150 100644 --- a/include/ebcl/inline/HashTables.hh +++ b/include/ebcl/inline/HashTables.hh @@ -185,6 +185,23 @@ inline V* T_KeyValueTable< K , V >::get( K const& k ) return &values_[ idx ]; } +template< typename K , typename V > +template< typename... ArgTypes > +V& T_KeyValueTable< K , V >::getOrCreate( + K const& k , + ArgTypes&&... args ) +{ + const uint32_t hash = ComputeHash( k ); + uint32_t idx = find( k , hash ); + if ( idx != T_HashIndex::INVALID_INDEX ) { + return values_[ idx ]; + } + + index_.add( hash ); + keys_.add( k ); + return values_.addNew( std::forward< ArgTypes >( args ) ... ); +} + /*----------------------------------------------------------------------------*/ template< typename K , typename V >