Search code examples
c++templatestemplate-specializationstring-literals

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


Solution

  • 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]) {}