gpt4 book ai didi

c++ - 字符串作为模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:54 28 4
gpt4 key购买 nike

虽然 C++ 标准不允许使用字符串文字作为模板参数,但允许这样的事情:

ISO/IEC 14882:2011

14.3.2 Template non-type arguments [temp.arg.nontype]

2 [ Note: A string literal (2.14.5) does not satisfy the requirements of any of these categories and thus is not an acceptable template-argument. [ Example:

template<class T, const char* p> class X { / ... / };

X<int, "Studebaker"> x1; // error: string literal as template-argument

const char p[] = "Vivisectionist";
X<int,p> x2; // OK

—end example ] —end note ]

那么为什么下面的代码在所有编译器(gcc 4.7.2、MSVC-11.0、Comeau)中都会给我一个错误?

template <const char* str>
void foo() {}

int main()
{
const char str[] = "str";
foo<str>();
}

最佳答案

倒回几行。

14.3.2/1:常量表达式 (5.19),指定具有静态存储持续时间和外部或内部链接的对象的地址。

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

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