12

I have a template function:

template<typename T>
void foo(const T& value) { bar(value); x = -1; }

I want to specialize it for a set of types:

template<>
void foo<char>(const char& value) { bar(value); x = 0; }
template<>
void foo<unsigned char>(const unsigned char& value) { bar(value); x = 1; }

It works ok. When I compile this:

template<>
void foo<char*>(const char*& value) { bar(value); x = 2; }

I get an error:

error C2912: explicit specialization; 'void foo(const char *&)' is not a specialization of a function template

Is it possible to specialize with char* pointer type parameter without typedef'ing it?

pingw33n
  • 12,292
  • 2
  • 37
  • 38

2 Answers2

20

Sure. Try this:

template<>
void foo<char*>(char* const& value) {...}

This is because const char* means pointer to const char, not a const pointer to char.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • You could also do this, right? `template<> void foo(const char* const& value) {...}` This kind of approach works for me, though I'm not finding it necessary to specify `` after `foo`. – Alan Mar 02 '17 at 22:00
3

You should generally just avoid function template specializations: you'll have far less problems if you provide non-template overloads instead. Read more: Why Not Specialize Function Templates?

UncleBens
  • 40,819
  • 6
  • 57
  • 90