FrozenHeart
FrozenHeart

Reputation: 20736

Strings as template arguments

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>();
}

Upvotes: 4

Views: 304

Answers (2)

mkluwe
mkluwe

Reputation: 4061

Note that the following modification works:

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

char str[] = "str";

int main() {
    foo<str>();
}

See http://www.comeaucomputing.com/techtalk/templates/#stringliteral for a short explanation.

Upvotes: 4

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

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.

Upvotes: 5

Related Questions