c++ - 模板参数字符串与 int

标签 c++ templates

<分区>

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

关于c++ - 模板参数字符串与 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543425/

相关文章:

c++ - 虚函数上未解析的外部符号

c++ - 将复杂参数放入 min 函数时出错?为什么?(Eclipse C++)

c++ - const 引用和虚拟模板继承

c++ - const 的未定义行为

c++ - 链接编译时链接到另一个库的库

c++ - 定义模板化运算符重载时出错

C++ 微软 : How to associate uuid/guid with template specialization

c++ - 使用 ctime 检索时间,包括时区

c++ - 类内模板化类的 Typedef

c++ - 推断大多数模板对象的参数,但在调用模板函数时与其他对象一起显式?