Possible Duplicate:
Strings as template arguments?
为什么第一个声明可以,但第二个声明不行?为什么 std::string
不合适?
template <typename T, T x> struct foo { };
using namespace std;
int main()
{
foo<int, 0> f_int; // ok
foo<string, ""> f_string; // not ok
}
我得到:
error: a non-type template parameter cannot have type 'std::basic_string<char>'
使用 clang++。
您不能简单地拥有 std::string
类型的模板参数。非类型模板参数的规则由标准定义如下 (§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
.
此外 (§14.1/7):
A non-type template-parameter shall not be declared to have floating point, class, or void type.
由于 std::string
是类类型,因此不允许实例化 foo
。