Yve*_*ves 7 c++ templates string-literals c++11 c++14
我正在尝试在 C++14 项目中传递文字字符串作为模板参数。谷歌告诉我,我可以这样做:
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>();
}
Run Code Online (Sandbox Code Playgroud)
它确实有效。
但是,如果我使用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>();
}
Run Code Online (Sandbox Code Playgroud)
现在不行了。编译器告诉我'Test::teststr' is not a valid template argument because 'Test::teststr' is a variable, not the address of a variable
。
嗯,我不知道这意味着什么。
编译器的错误消息很清楚:
错误:“Test::teststr”不是有效的模板参数,因为“Test::teststr”是变量,而不是变量的地址
所以你需要:
#include <iostream>
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>();
}
Run Code Online (Sandbox Code Playgroud)
然后它就起作用了- 要点是变量[的内容]不是编译时常量,而变量的地址(如果它是静态或全局变量)是。
这只是根据c++的规则:
\n\n\nTemplate non-type arguments.
\n
\nFor pointers to objects, the template arguments have to designate the address of a complete object with static storage duration and a linkage (either internal or external)
https://en.cppreference.com/w/cpp/language/template_parameters
\nA global array of characters has linkage while a string literal doesn\xe2\x80\x99t.
\nIn C++20 this has been changed and you can use string literals as template parameters.
归档时间: |
|
查看次数: |
913 次 |
最近记录: |