Strings as template arguments

While C ++ standards do not allow string literals to be used as template arguments, things are allowed:

ISO / IEC 14882: 2011

14.3.2 Argument template non-type [temp.arg.nontype]

2 [Note: the string literal (2.14.5) does not satisfy the requirements of any of these categories and, therefore, the Template argument is not acceptable. [Example:

template<class T, const char* p> class X { / ... / };

X<int, "Studebaker"> x1; // error: string literal as template-argument

const char p[] = "Vivisectionist";
X<int,p> x2; // OK

-end example] -end note]

So, why does the following code give me an error in all compilers (gcc 4.7.2, MSVC-11.0, Comeau)?

 template <const char* str> void foo() {} int main() { const char str[] = "str"; foo<str>(); } 
+4
source share
2 answers

Rewind a few lines.

14.3.2 / 1: the constant expression (5.19), which denotes the address of an object with a static storage duration and external or internal communication.

+5
source

Please note that the following modification works:

 template <const char* str> void foo() {} char str[] = "str"; int main() { foo<str>(); } 

For a brief explanation, see http://www.comeaucomputing.com/techtalk/templates/#stringliteral .

+4
source

All Articles