Re: Is const char* an exception in a template specification?
On 18 Mai, 03:12, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
Hi!
I would like to do the following similar to the second half of 35.9 in
the FAQ http://www.parashift.com/c++-faq-lite/templates.html
template<class T>
class A {
[snip]
template<>
class A<const char*> {
[snip]
template<class T>
void foo( const T& t )
{
A<T> bar(t);
}
main()
{
foo( "Hello" );
}
But the code does not use my specialized const char* template.
This is because of the type deduction rules, you taking 't' by
reference, and the literal "Hello" being an lvalue of type "const char
[6]". If you let the compiler deduce the type T and take 't' by
reference it'll use T = const char[6] instead of T = const char*.
However, if you take 't' by value T is going to be a pointer to const
char.
To solve this problem you can either be explicit w.r.t. to T:
int main() // <-- Note that main returns an int
{
foo<const char*>("Hello"); // <-- specify T
}
of apply a bit of meta-programming inside foo ? la
// type transforming compile-time function "ptr_decay"
template<typename T> struct ptr_decay { typedef T type; };
template<typename T> struct ptr_decay<T[]> { typedef T* type; };
template<typename T, std::size_t N>
struct ptr_decay<T[N]> { typedef T* type; };
template<class T>
void foo( const T& t )
{
typedef typename ptr_decay<T>::type T2;
// T2 will be a pointer if T is an array
A<T2> bar(t);
// If t is a reference to an array and
// A<T2> takes a pointer as constructor
// argument, t will decay to a pointer.
}
int main() // <-- Note that main returns an int
{
foo("Hello");
}
which should use your specialization of A for pointers to const char.
Am I forced to write also the following function?
void foo( const char* t )
No.
Or can I solve it in some other manner?
Yes. See above.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]