【发布时间】:2020-08-23 07:23:59
【问题描述】:
C 有一个有趣的技巧,一个名字可以用来声明一个类型和一个函数:
struct foo {};
void foo(void);
现在,每当我写 foo 时,编译器都会假定我指的是函数,除非我在它前面加上 struct:
foo(); // call void foo(void)
struct foo bar; // declare variable of type struct foo
即使使用命名空间和嵌套,这在 C++ 中也很有效! 但它不适用于模板:
template <typename> void bar(void);
template <typename> struct bar {};
// error: conflicting declaration of template struct bar
// previous declaration: template void bar()
为什么?
我们已经开始处理依赖上下文中的消歧器了:
typename foo<A>::b();
foo<A>::template b<C>();
将常规规则应用于此类模棱两可的模板名称似乎并不难。
假设同名对我很重要。我能以某种方式完成这项工作吗?
【问题讨论】:
-
如果您正在寻找 C++ 标准中的“章节和诗句”,您可能需要添加
language-lawyer标签,并且可能需要交叉引用 C 标准中的细微差别、差异和相似之处。 -
好建议。完成。
-
因为它是 struct hack,而不是 template hack。
标签: c++ templates struct language-lawyer name-lookup