Re: Explicit specialization of char []?
Dave Johansen <davejohansen@...com> writes:
What is the syntax for doing an explicit specialization of a char []?
When I do an explicit specialization on "const char *" or "char *", it
doesn't handle an inline declared character array and calls the
default template method.
For the purposes of template argument deduction an array of characters
is a different type from a pointer to a character array, so as a first
try this is always going to fail.
I'm using Visual C++ Express 2008 and below is an example of what I'm
trying to do.
Thanks,
Dave
#include <iostream>
template<typename T>
void func(const T &value)
{
std::cout << "T: " << value << std::endl;
}
template<>
void func<const char *>(const char * const &value)
{
std::cout << "CCS: ";
if (value != NULL)
std::cout << value << std::endl;
else
std::cout << "NULL" << std::endl;
}
// the following specialization will be chosen for str2
template<>
void func<char[9]>(const char (&value)[9])
{
std::cout << "CCA: ";
std::cout << value << std::endl;
}
int main(int argc, char *argv[])
{
const char *str1 = "testing1";
const char str2[] = "testing2";
func(str1);
func(str2);
return 0;
}
Note, however, that the array bounds is part of the type that is used to
match the new specialization. So, for example:
const char str3[] = "testing_3"; // char [10]
func(str3);
would again match only the primary template. Furthermore, IIRC, you
can't have a (cv) reference to an array of unknown bound, so it's not
possible to write the new specialization to match char arrays of
arbitrary size.
So, the bottom line is probably that you're better off following
tonydee's suggestion and providing an overload rather than a
specialization. (Unfortunately partial specialization of function
templates is not allowed, otherwise we might be tempted to write:
template<size_t N>
void func<char[N]>(const char (&value)[N]);
but the fact that we /can/ overload means that our inability to
partially specialize here is not much of a limitation after all.)
Regards
Paul Bibbings