简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM