有一个模板类A,我想用它制作两个具体的类:B和C
#include <iostream>
using namespace std;
template<const char* s = "hello">
class A {
public:
void foo();
};
template<const char* s>
void A<s>::foo() {
cout << s;
}
typedef A<" world"> B;
class C : public A<"!\n"> {};
int main() {
A<"hello"> a;
B b;
C c;
a.foo();
b.foo();
c.foo();
return 0;
}
但我得到一个错误:
prog.cpp:15:19: error: ‘" world"’ is not a valid template argument for type ‘const char*’ because string literals can never be used in this context
typedef A<" world"> B;
^
prog.cpp:17:25: error: ‘"!\012"’ is not a valid template argument for type ‘const char*’ because string literals can never be used in this context
class C : public A<"!\n"> {};
^
prog.cpp: In function ‘int main()’:
prog.cpp:20:11: error: ‘"hello"’ is not a valid template argument for type ‘const char*’ because string literals can never be used in this context
A<"hello"> a;
^
prog.cpp:23:4: error: request for member ‘foo’ in ‘a’, which is of non-class type ‘int’
a.foo();
^~~
prog.cpp:24:4: error: request for member ‘foo’ in ‘b’, which is of non-class type ‘B {aka int}’
b.foo();
^~~
prog.cpp:25:4: error: ‘class C’ has no member named ‘foo’
c.foo();
^~~
如果模板中的 yA是整数而不是字符串,则代码可以正常工作。
使用模板非类型参数时有很多限制,包括:
此限制意味着字符串文字不能用作模板参数:
因为他们既没有内部链接也没有外部链接。这意味着该标准不保证将相同的字符串文字放置在同一地址,将实现的选择留给编译器实现者。因此,
A<"hello"> a;在不同的代码片段中使用可能会导致不同模板的实例化。处理了错误的原因后,我们可以尝试修复它:我们需要将指向具有静态存储持续时间和内部或外部链接的对象的指针作为模板参数传递。