更新时间:2022-12-16 09:58:27
这意味着你不能像下面这样做
void foo()
{
template< typename T> // Error
T something;
}
模板声明只允许在全局,命名空间或类范围。 :)
其背后的原因是什么?
$ b b
这是不允许的,因为标准说。
ISO C ++ - 98 (第14.2节)
模板声明只能作为命名空间或类作用域声明。
这是否有意义?
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?