Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ specialized template function receiving literal string

I am writting a template method which has many specializations.

class FieldValue
{
public:
   ...
   template< typename T >
   void Set( const T& value );
   ...
};

One of them is:

template <>
void FieldValue::Set< const char* >( const char* const& value )
{
   ...
}

But when I try to call

FieldValue fieldValue;
fieldValue.Set( "literal string" );

it expects an specialization for const char[14] which is the length of "literal string", not a const char*

Is there any work around this without the need to cast it to const char*?

UPDATE

After Rakete1111's recommendation, that's what I did:

class FieldValue
{
public:
   ...
   template< typename T >
   void Set( const T& value );

   template< std::size_t N >
   void Set( const char( &value )[ N ] )
   {
     Set( static_cast< const char* >( value ) );
   }
   ...
};

This will end up calling the const char* specialization

like image 212
Matheus Medeiros Avatar asked Feb 27 '18 20:02

Matheus Medeiros


1 Answers

If you were asking this for a class, I would have answered that you can use partial specialization:

template<std::size_t N>
struct Foo<const char (&)[N]> {};

But that doesn't work for function templates. Instead, you can overload them:

template<std::size_t N>
void FieldValue::Set(const char (&Value)[N]) {}
like image 126
Rakete1111 Avatar answered Sep 30 '22 01:09

Rakete1111