3

Possible Duplicate:
Strings as template arguments?

Why the first declaration is OK but the second is not? Why std::string is not suitable?

template <typename T, T x> struct foo { };

using namespace std;

int main()
{
    foo<int, 0> f_int;              // ok
    foo<string, ""> f_string;      // not ok
}

I get:

error: a non-type template parameter cannot have type 'std::basic_string<char>'

using clang++.

Community
  • 1
  • 1
Cartesius00
  • 23,584
  • 43
  • 124
  • 195

2 Answers2

8

You simply cannot have a template parameter of type std::string. The rules for non-type template parameters are defined by the standard as follows (§14.1/4):

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.

In addition (§14.1/7):

A non-type template-parameter shall not be declared to have floating point, class, or void type.

As std::string is a class type, your instantiation of foo is not allowed.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
5

Because a non-type template parameter (ugly name for "value") should be computable at compile time and std::string is not (it may require dynamic memory allocation thus its constructor is not constexpr).

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722