Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings as template arguments

Tags:

c++

While the C++ standards doesn't allow to use string literals as template-arguments, it is allowed things like this:

ISO/IEC 14882:2011

14.3.2 Template non-type arguments [temp.arg.nontype]

2 [ Note: A string literal (2.14.5) does not satisfy the requirements of any of these categories and thus is not an acceptable template-argument. [ 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 the following code gives 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>();
}
like image 776
FrozenHeart Avatar asked Jan 14 '23 13:01

FrozenHeart


1 Answers

Rewind a few lines.

14.3.2/1: a constant expression (5.19) that designates the address of an object with static storage duration and external or internal linkage.

like image 157
n. 1.8e9-where's-my-share m. Avatar answered Jan 26 '23 00:01

n. 1.8e9-where's-my-share m.