gpt4 book ai didi

c++ - 字符串文字不能作为 C++ 中的模板参数接受吗?

转载 作者:太空狗 更新时间:2023-10-29 23:05:18 28 4
gpt4 key购买 nike

第 724 页,第 25 章,C++ 编程语言

用作模板参数的指针必须采用 &of 形式,其中 of 是对象或函数的名称,或者采用 f 形式,其中f 是函数的名称。指向成员的指针必须采用 &X::of 形式,其中 of 是成员的名称。特别是,字符串文字作为模板参数是 Not Acceptable :

template<typename T, char∗ label>
class X {
// ...
};
X<int,"BMW323Ci"> x1; // **error : string literal as template argument**
char lx2[] = "BMW323Ci";
X<int,lx2> x2; // OK: lx2 has exter nal linkage

第 725 页,第 25 章,C++ 编程语言

这在与默认模板参数结合时变得特别有用(§25.2.5);为了示例:

template<typename T, T default_value = T{}>
class Vec {
// ...
};
Vec<int,42> c1;
Vec<int> c11; // default_value is int{}, that is, 0
Vec<string,"fortytwo"> c2; // **I'm confused!**
Vec<string> c22; // default_value is string{}; that is, ""

最佳答案

template<typename T, T default_value = T{}>
class Vec {
// ...
};
Vec<string,"fortytwo"> c2;
Vec<string> c22;

涉及 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.

关于c++ - 字符串文字不能作为 C++ 中的模板参数接受吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20066104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com