C++ 在类中使用typedef覆盖现有类型
我想用typedef覆盖一个类型。这样做的基本原理是,我的一个类有很多模板,我想用模板化类替换对该类的所有调用(这样在另一个类中C++ 在类中使用typedef覆盖现有类型,c++,C++,我想用typedef覆盖一个类型。这样做的基本原理是,我的一个类有很多模板,我想用模板化类替换对该类的所有调用(这样在另一个类中Achild意味着Achild。但是,我得到了一个错误 template <typename T> class Achild { public: Achild<T>() = default; }; class Foo { typedef Achild<int> Achild;
Achild
意味着Achild
。但是,我得到了一个错误
template <typename T>
class Achild
{
public:
Achild<T>() = default;
};
class Foo
{
typedef Achild<int> Achild;
public:
Foo() = default;
};
int main()
{
auto foo = new Foo();
}
模板
阶级斗争
{
公众:
Achild()=默认值;
};
福班
{
类型def-Achild-Achild;
公众:
Foo()=默认值;
};
int main()
{
自动foo=新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
new_test.cpp:12:22:错误:声明'typedef类Achild Foo::Achild'[-fppermissive]
类型def-Achild-Achild;
^~~~~~
new_test.cpp:2:10:错误:将“Achild”的含义从“class Achild”[-fppermissive]更改为“Achild”
阶级斗争
如何使其工作?该示例仅用于示例,我这样做的原因还与我如何使其与现有代码库工作有关。您正在使用类型本身对该类型进行别名(
Achild
自您在类中声明以来已经是一个类型)。您应该改为:
使用Child=Achild;
请注意,您还应该使用关键字
using
而不是typedef
,因为它在C++
中是等效的(而且更健壮)。请参阅。如果您投了反对票,请至少添加一条注释说明您为什么这样做。谢谢。这是在msvc上编译的,因此我相信它在iso上会起作用