关于char*类型的模版参数问题

rootfinger 2003-09-26 01:18:45
定义了一个模如下:
template <const char *NAME>
struct A
{
void DispName()
{ printf("%s\n", NAME);}
};

int main()
{
A<"First Name"> a; //编译失败,?
a.DispName();
}

编译失败,为什么?我用的是vc6.0,是vc的问题吗?
...全文
124 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sevecol 2003-09-26
  • 打赏
  • 举报
回复
template <char const* name>
class MyClass {

};

MyClass<"hello"> x; // ERROR: string literal "hello" not allowed
You cannot use a global pointer either:

template <char const* name>
class MyClass {

};

char const* s = "hello";

MyClass<s> x; // ERROR: s is pointer to object with internal linkage
However, the following is possible:

template <char const* name>
class MyClass {

};

extern char const s[] = "hello";

MyClass<s> x; // OK
The global character array s is initialized by "hello" so that s is an object with external linkage.

ezhou 2003-09-26
  • 打赏
  • 举报
回复
想要可用分多,坚持上csdn。
ljianq 2003-09-26
  • 打赏
  • 举报
回复
你声明的const啊。
rootfinger 2003-09-26
  • 打赏
  • 举报
回复
问题解决了,马上结贴。

ps:我是新来的,能不能给点可用分?
wingfiring 2003-09-26
  • 打赏
  • 举报
回复
你可以改成这样:
const char* name = "First Name"
int main()
{
A<name> a;
a.DispName();
}

C++ 98的标准里有说明,char * 作为模版参数的时候,
而不允许使用常量,必须是变量。

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧