加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么模板不能采用函数本地类型?

发布时间:2020-12-16 03:32:22 所属栏目:百科 来源:网络整理
导读:在C中,有一个函数本地类型的函数是可以的: int main() { struct S { static void M(const S s) { } }; S s; S::M(s);} 但是没有确定的模板可以: templatetypename T void Foo(const T t) { }int main() { struct S { } s; Foo(s); // Line 5: error: no ma
在C中,有一个函数本地类型的函数是可以的:
int main() {
  struct S { static void M(const S& s) { } };
  S s;
  S::M(s);
}

但是没有确定的模板可以:

template<typename T> void Foo(const T& t) { }

int main() {
  struct S { } s;
  Foo(s);   // Line 5: error: no matching function for call to 'Foo(main()::S&)'
}

14.3.1 paragraph 2 in the c++ standard.

A type with no linkage […] shall not be used as a template-argument for a template type-parameter

为什么C不允许这样做?

到目前为止我听到的最好的解释是内部类型没有链接,这可能意味着将它们作为arg的函数必须没有链接.但是我没有理由看到模板实例化必须具有链接.

附:请不要只说“thats not allowed because the standard says it’s not”

解决方法

我猜这是因为它需要在函数范围内有效地实例化模板,因为这是可见的类型.但是,同时,模板实例化应该表现为它们位于定义模板的范围内.我确信这可以以某种方式处理,但如果我是对的,标准组织决定不对编译器编写者施加这种负担.

类似的决定是向量< vector< int>>的原因.每个标准的语法无效;检测到构造需要编译器词法分析器和解析器阶段之间的某些交互.但是,这种情况正在发生变化,因为C 0x标准民众发现所有编译器都在检测它,无论如何都要发出合理的错误信息.

我怀疑如果要证明允许这种构造实现起来是微不足道的,并且它没有在语言范围规则中引入任何含糊之处,那么有一天你可能会看到标准也发生了变化.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读