将 typedef 放在使用 class 本身作为模板参数的 class 中是否有效?
Is it valid to place a typedef inside a class that uses class itself as template parameter?
如果 typedef 使用它所在的 class 作为参数,那么将 typedef 放在 class 中是否有任何缺陷?
#include <memory>
class Foo{
public:
typedef std::shared_ptr<Foo> shared_ptr;
}
void main(){
Foo x;
Foo::shared_ptr p = std::make_shared<Foo>();
}
上面的代码对我有用(clang),但我想知道标准是否有关于它的任何内容。
Foo
class 中的 typedef
是 声明 而 不是定义 所以它被允许做你正在做的事情。如果它是一个定义,它是不允许的,因为 Foo
class 的定义在右大括号之前是不完整的。
6.1 Declarations and definitions [basic.def]
2 A declaration is a definition unless
...
(2.9) — it is a typedef
declaration (10.1.3),
但是如果你这样做了:
class Foo{
public:
Foo f; //A definition
}
Foo f
将被视为定义,而 compiler will issue an error 如:
error: field has incomplete type 'Foo'
Foo f;
^
<source>:1:7: note: definition of 'Foo' is not complete until the closing '}'
class Foo{
如果 typedef 使用它所在的 class 作为参数,那么将 typedef 放在 class 中是否有任何缺陷?
#include <memory>
class Foo{
public:
typedef std::shared_ptr<Foo> shared_ptr;
}
void main(){
Foo x;
Foo::shared_ptr p = std::make_shared<Foo>();
}
上面的代码对我有用(clang),但我想知道标准是否有关于它的任何内容。
Foo
class 中的 typedef
是 声明 而 不是定义 所以它被允许做你正在做的事情。如果它是一个定义,它是不允许的,因为 Foo
class 的定义在右大括号之前是不完整的。
6.1 Declarations and definitions [basic.def]
2 A declaration is a definition unless
...(2.9) — it is a
typedef
declaration (10.1.3),
但是如果你这样做了:
class Foo{
public:
Foo f; //A definition
}
Foo f
将被视为定义,而 compiler will issue an error 如:
error: field has incomplete type 'Foo' Foo f; ^ <source>:1:7: note: definition of 'Foo' is not complete until the closing '}' class Foo{