gpt4 book ai didi

c++ - 为什么模板定义中不允许使用结构?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:03 26 4
gpt4 key购买 nike

以下代码产生错误error: ‘struct Foo’ is not a valid type for a template constant parameter:

template <struct Foo>
struct Bar {

};

为什么会这样?

template <class Foo>
struct Bar {

};

工作得很好,甚至可以接受结构作为参数。

最佳答案

这只是语法规则的产物——语法只允许您使用 classtypename 关键字来指示类型模板参数。否则参数必须是“非类型”模板参数(基本上是整数、指针或引用类型)。

我想 Stroustrup(以及他可能从中获取输入的任何其他人)决定没有必要将 struct 作为关键字来指示类型模板参数,因为不需要向后兼容与 C.

事实上,我的内存 (我回家后必须读书) 是在添加typename时表示模板类型参数,Stroustrup 希望为此目的使用 class 关键字(因为它很困惑),但是依赖它的代码太多了。


编辑:

事实证明这个故事更像是(来自 blog entry by Stan Lippman ):

The reason for the two keywords is historical. In the original template specification, Stroustrup reused the existing class keyword to specify a type parameter rather than introduce a new keyword that might of course break existing programs. It wasn't that a new keyword wasn't considered -- just that it wasn't considered necessary given its potential disruption. And up until the ISO-C++ standard, this was the only way to declare a type parameter.

Reuses of existing keywords seems to always sow confusion. What we found is that beginners were [wondering] whether the use of the class constrained or limited the type arguments a user could specify to be class types rather than, say, a built-in or pointer type. So, there was some feeling that not having introduced a new keyword was a mistake.

During standardization, certain constructs were discovered within a template definition that resolved to expressions although they were meant to indicate declarations

...

The committee decided that a new keyword was just the ticket to get the compiler off its unfortunate obsession with expressions. The new keyword was the self-describing typename.

...

Since the keyword was on the payroll, heck, why not fix the confusion caused by the original decision to reuse the class keyword. Of course, given the extensive body of existing code and books and articles and talks and postings using the class keyword, they chose to also retain support for that use of the keyword as well. So that's why you have both.

关于c++ - 为什么模板定义中不允许使用结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2520130/

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