c++ - Templatized [] or () operator overload - possible without using type as arg? -


in same way can this...

template< typename t > t getvalue( const int index ) const;  char c = getvalue< char >( 0 ); 

...is possible this:

template< typename t > t operator[]( const char* key ) const;  char c = getvalue< char >( "some key" );    // *** doesn't compile *** 

...or this:

template< typename t > t foo::operator()( const char* key ) const;  char c = foo< char >( "some key" );    // *** doesn't compile *** 

the 2 examples above don't compile due < char > , without "can't deduce type" error (i understand why case).

the closest can specify 'default value' gets rid of "can't deduce type" error, this:

template< typename t > t operator()( const char* key, const t& defaultvalue ) const;  char c = foo( "some key", 'x' ); 

but, isn't want.

edit

essentially, i'm doing:

class collection {   ...    template< typename t >   t operator[]( const char* key ) const;    template< typename t >   void add( const char* key, const t& value );    ... } 

and how i'd use it:

collection col; col.add( "some key", 123 ); col.add( "another key", 'x' ); col.add( "and another", 1.23 );  char c = col< char >[ "another key" ]; 

if understood correctly want achieve this:

struct s {    template< typename t >    t operator[]( const char* key ) const {        return key[0];    }    template< typename t >    t operator()( const char *key) const {        return key[0];    } };  int main() {    s s;    char c = s.operator[]<char>("some key");    c = s.operator()<char>("some key");    (void)c; } 

[live demo]


if syntax doesn't fit application try use tag dispatching:

struct s {    template< typename t >    t operator()(const char *key, t) const {        return key[0];    } };  int main() {    s s;    char c = s("some key", char{});    (void)c; } 

[live demo]

this can harder apply operator[] can take 1 argument.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -