c++/10037: String literal has type `char*' when passed as parameter to function template

bsamwel@xs4all.nl bsamwel@xs4all.nl
Wed Mar 12 14:56:00 GMT 2003


>Number:         10037
>Category:       c++
>Synopsis:       String literal has type `char*' when passed as parameter to function template
>Confidential:   no
>Severity:       serious
>Priority:       medium
>Responsible:    unassigned
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Wed Mar 12 14:56:00 UTC 2003
>Closed-Date:
>Last-Modified:
>Originator:     Bart Samwel
>Release:        g++.real (GCC) 3.2.3 20030309 (Debian prerelease)
>Organization:
>Environment:
Debian unstable ("sid") as of 12/03/03. i386 architecture.
>Description:
Compiling the following code:

--------------------------SNIP---------------------------

template<typename T>
void foo(const T& obj);

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

int main()
{
  foo ("bar");
}

--------------------------SNIP---------------------------

yields this output:

--------------------------SNIP---------------------------

bsamwel@zappa:~/test$ g++ -Wwrite-strings -Wall test38.cc
/tmp/ccEI3tbA.o(.text+0x1f): In function `main':
: undefined reference to `void foo<char[4]>(char[4] const&)'
collect2: ld returned 1 exit status

--------------------------SNIP---------------------------

I would expect the string constant "bar" to be seen as type "const char*", which would make it find the specialisation.
However, it treats the string constant as type "char*", which makes it miss the specialisation because there are two implicit casts involved. Adding a cast to (const char*) in front of the string literal makes it find the specialisation. This is a bug in g++ and it should be fixed. In addition, no warning is given for the deprecated conversion to char*, while I explicitly passed the flag requesting the compiler to warn me when this situation occurred.

BTW, the issue whether adding a const should count as an implicit conversion is separate from this one. I personally am of the opinion that it greatly complicates programming if adding a const is included in the number of implicit conversions; I would much rather have it that the limit be set at "one implicit conversion that is not the addition of a const, plus an unlimited number of added consts". I regard this as a defect in the standard that should be fixed, because it leads exactly to the kind of situations found here - in this case, the specialisation will not be used if I pass foo any object of type char*, only because the argument expects a const char * _const_ instead of a const char*, which is completely not what I would expect as a client!
>How-To-Repeat:
Compile the bit of code supplied in the description using the command shown in the output.
>Fix:

>Release-Note:
>Audit-Trail:
>Unformatted:



More information about the Gcc-prs mailing list