为什么char的数组是模板参数,而const char*可以
我正在尝试将字面字符串作为C ++ 14项目中的模板参数。 Google告诉我,我可以按照以下操作:
struct Test {
static const char teststr[];
template<const char* str>
void p() {std::cout << str;}
};
const char Test::teststr[] = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
它确实有效。
但是,如果我使用 const char*
,而不是 const char []
。它行不通。
struct Test {
static const char* teststr;
template<const char* str>
void p() {std::cout << str;}
};
const char* Test::teststr = "Hello world!";
int main() {
Test t;
t.p<Test::teststr>();
}
现在它不起作用。编译器告诉我,'test :: teststr'不是有效的模板参数,因为'test :: teststr'是变量,而不是变量的地址
。
好吧,我不知道这是什么意思。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器的错误消息已经足够清楚:
因此您需要:
然后它的工作 - 要点是,变量的内容不是编译时常数,而可变的地址(如果它是静态或全局变量) 是。
The error message from the compiler is clear enough:
So you need:
And then it works - the point being that [the contents of] a variable is not a compile-time constant, whereas the address of a variable (if it's a static or global variable) is.
这只是根据C ++的规则:
https://en.cppreference.com/w/cpp/language/template/template_parameters
全局字符阵列具有链接,而字符串则没有。
在C ++ 20中,这已更改,您可以将字符串文字用作模板参数。
This is just according to the rules of c++:
https://en.cppreference.com/w/cpp/language/template_parameters
A global array of characters has linkage while a string literal doesn’t.
In C++20 this has been changed and you can use string literals as template parameters.
问题是,在您的示例的情况下,静态数据成员
teststr
是一种指针类型,具有 string字符串文字的地址不允许可以从下面的引用语句中看到,:
因此,在您的示例2
teststr
的情况下,由于它是具有具有指针类型,因此无法使用字符串文字的地址“ Hello World!”
。The problem is that in case 2 of your example the static data member
teststr
is a pointer type that has the address of a string literal which is not allowed by the standard as can be seen from the quoted statement below ,From non-type template parameter's documentation:
Thus, in case 2 of your example
teststr
cannot be used as it is a pointer type that has the address of the string literal"Hello world!"
.