为什么不能在函数中声明模板? [英] Why can't templates be declared in a function?

查看:255
本文介绍了为什么不能在函数中声明模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 C ++范本:完整指南,并说




请注意,模板不能在函数中声明为


给予书或外部资源中任何其他章节的解释和/或交叉引用。



有人可以解释这个问题。也许它在后面的书中解释,但还没有。



例如:

  int main()
{
class DummyClass //编译ok
{
int object;
};

template< typename T> // compile errorexpected primary-expression beforetemplate
class DummyTemplate
{
T object;
};

return 0;
}



我不明白gcc的错误信息。错误消息说:

 模板之前的预期主表达式
pre>

解决方案

这意味着你不能像下面这样做

  void foo()
{
template< typename T> // Error
T something;
}

模板声明只允许在全局,命名空间或类范围。 :)


其背后的原因是什么?



$ b b

这是不允许的,因为标准说。



ISO C ++ - 98 (第14.2节)



< blockquote>

模板声明只能作为命名空间或类作用域声明。


这是否有意义?


Reading C++ Templates: The Complete Guide and it says

Note that templates cannot be declared in a function

It does not give explanation and/or cross reference to any other chapter in the book or external resource.

Could someone help in explaining this. Probably it is explained later in the book but not there yet. If explained earlier, I must have missed it.

Example:

int main()
{
  class DummyClass  //  This compiles ok
  {
    int object;
  };

  template <typename T> //  compile error "expected primary-expression before "template""
  class DummyTemplate
  {
    T object;
  };

  return 0;
}

I do not understand the error message from gcc either. The error message says:

expected primary-expression before "template"

解决方案

It means you cannot do something like the following

  void foo()
  {
       template <typename T> //Error
       T something;
  }

Template declarations are only permitted at global, namespace, or class scope. :)

What is the reasoning behind it?

It is not allowed because the Standard says so .

ISO C++-98 (Section 14.2)

A template declaration can appear only as a namespace or class scope declaration.

Does that make sense?

这篇关于为什么不能在函数中声明模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆