Tuesday 4 February 2014

String as a template parameter in C++03

So you want to instantiate your template with a string literal, but you can do this only by defining it as a constant. This code should work:

#include <iostream>
template <const char* p> Foo () { std::cout << p; }
extern const char s[] = "Hello world!";
void main () { Foo <s> (); }

The tricky part here is extern for s. C++03 requires template arguments to have external linkage. I can't remember any other reasons for using extern const in production code. The reason is that the C++ specs in that point are simply over-restrictive. Fortunately, C++11 doesn't have such a mess.

No comments:

Post a Comment