I know the only way to pass a string literal as template argument is to declare it before:
file a.h
#ifndef A_H
#define A_H
#include <string>
char EL[] = "el";
template<char* name>
struct myclass
{
std::string get_name() { return name; }
};
typedef myclass<EL> myclass_el;
#endif
file a.cpp
#include "a.cpp"
main.cpp
#include "a.h"
...
g++ -c a.cpp
g++ -c main.cpp
g++ -o main main.o a.o
and I got:
a.o:(.data+0x0): multiple definition of `EL'
main.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
I can’t declare EL as external and I want to keep the a.cpp. Solutions?
Let’s start with what the Standard says for the benefit of all, from 14.3.2 Template non-type arguments [temp.arg.nontype] (C++03 Standard):
Emphasis mine for the relevant parts.
Additionally, paragraph 5 lists the conversions that are allowed and one of them is array to pointer decay. Paragraph 2 is even a note that showcases a similar use of
char*as that of the OP.All that is left is how to have an object in a header with external linkage and no errors. The usual way is a declaration in the header, and one and only one definition in one TU.
Note that
staticis not a possibility because of the requirement that the object have external linkage. The unnamed namespace is to be preferred if the intent is to have a separate object per TU.For the curious, C++0x relaxed the requirement that an object have external linkage to be a valid parameter. (My copy of GCC doesn’t support that yet.) String literals are inexplicably still forbidden to appear as template arguments.