在类内部用typedef覆盖现有类型

Overwriting existing type with typedef inside a class

本文关键字:类型 覆盖 typedef 内部      更新时间:2024-03-29

我想用typedef覆盖一个类型。这样做的理由是,我的一个类有很多模板,我想用模板化的类替换对该类的所有调用(这样在另一个类中Achild意味着Achild<T>。但是,我得到了一个错误。

template <typename T>
class Achild
{
public:
Achild<T>() = default;

};
class Foo
{
typedef Achild<int> Achild;
public:
Foo() = default;
};
int main()
{
auto foo = new Foo();
}

我得到以下错误:

new_test.cpp:12:22: error: declaration of ‘typedef class Achild<int> Foo::Achild’ [-fpermissive]
typedef Achild<int> Achild;
^~~~~~
new_test.cpp:2:10: error: changes meaning of ‘Achild’ from ‘class Achild<int>’ [-fpermissive]
class Achild

我怎样才能让它发挥作用?该示例仅用于示例,我这样做的原因还与如何使用现有的代码库有关。

您正在将类型本身别名(Achild自从在类中声明以来就已经是一个类型了(。你应该改为:

using Child = Achild<int>;

请注意,您还应该使用关键字using而不是typedef,因为它在C++中是等效的(而且更健壮(。请参阅';typedef';和';使用';在C++11中?。