本地类:C ++ 03 vs. C ++ 11 [英] Local classes : C++03 vs. C++11
问题描述
C ++ 11中本地类的用法有什么变化吗?
Is there any change in the usage of local class in C++11?
在C ++ 03中似乎不能使用局部类作为模板参数
It seems in C++03 local classes cannot be used as template argument (I recall that).
Consider this code,
类型名T> void f(const T&){}
//注意:S是在main()中定义的局部类。 f(S()); } //我想要推导模板参数。
template<typename T> void f(const T&) {}
//Note : S is a local class defined inside main()
int main() { struct S{}; f(S()); } //I want template argument to be deduced.
但它给出了编译错误(C ++ 03模式),说( ideone ):
But it gives compilation error (C++03 mode), saying (ideone):
prog.cpp:4:错误:无匹配函数对于调用'f(main():: S)'
prog.cpp:4: error: no matching function for call to ‘f(main()::S)’
但是,模式( ideone ),这对我有意义,否则lambda不会工作。所以我想,至少有这种变化在使用本地类。我对吗?有关本地类的其他更改有哪些?
However, it compiles fine when compiling it in C++11 mode (ideone), which makes sense to me, otherwise lambda wouldn't work. So I guess that there is at least this change in the usage of local classes. Am I right? What are other changes concerning local classes?
请引用标准的相关文本(C ++ 03和C ++ 11两者),以便读者可以比较自己,
Please quote the relevant text from the Standards (C++03 and C++11 both) so readers can compare themselves, and for future reference.
推荐答案
通过在两种标准中比较§14.3.1/ 2,可以看出差异。
The differences are visible by comparing §14.3.1/2 in both standards.
-
C ++ 03
C++03
没有链接的类型,未命名的类型或从这些类型中任何一个复合的类型都不应该将
用作模板类型参数的模板参数。 [示例:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter. [Example:
template <class T> class X { /* ... */ };
void f()
{
struct S { /* ... */ };
X<S> x3; // error: local type used as template-argument
X<S*> x4; // error: pointer to local type used as template-argument
}
-end example] [注意:模板类型参数可能是不完整的类型(3.9)。 ]
—end example] [Note: a template type argument may be an incomplete type (3.9). ]
C ++ 0x(n3290)
C++0x (n3290)
[示例:
[ Example:
template <class T> class X { };
template <class T> void f(T t) { }
struct { } unnamed_obj;
void f() {
struct A { };
enum { e1 };
typedef struct { } B;
B b;
X<A> x1; // OK
X<A*> x2; // OK
X<B> x3; // OK
f(e1); // OK
f(unnamed_obj); // OK
f(b); // OK
}
:模板类型参数可能是不完整的类型(3.9)。 - end note]
— end example ] [ Note: A template type argument may be an incomplete type (3.9). — end note ]
C ++ 03明确禁止模板类型中的本地类参数。 C ++ 11没有,甚至包括有效使用这样的例子。
C++03 explicitly disallows local classes in template type arguments. C++11 doesn't, and even includes an example of a valid use of such.
这篇关于本地类:C ++ 03 vs. C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!