Home > Article > Backend Development > C++ error: Derived from template instantiation type is not allowed, how to solve it?
In the C programming language, when we use template instantiated types in derived classes, we may encounter the compiler error "Derived from template instantiated types not allowed" question. The reason for this error is that we are trying to derive a new subclass from a template instantiated type, which is not itself a class. This article will explain the cause of the error and provide a solution to the problem.
1. Cause of error
Template is a general programming tool that can be used to create classes or functions and can be instantiated according to different data types. When using templates, template parameters need to be specified. In C, when using a class template, the class name must be followed by a parameter list. For example:
template<typename T> class MyClass { //... };
When we use this class template, we need to provide a specific type:
MyClass<int> myObj;
This will create an int specialized version of the MyClass template.
However, when we use template instantiation types in derived classes, we will encounter the above error, for example:
template<typename T> class MyClass { //... }; class MyDerivedClass: public MyClass{ //... };
This code will prompt the error "Derived from template instances are not allowed." type".
The reason for this error is that MyClass
2. Solution
In order to solve this problem, we can use template parameters to specify the class to be derived. For example, if we want to derive a new class from MyClass
template<typename T> class MyClass { //... }; templateclass MyDerivedClass: public MyClass { //... };
This will avoid errors.
In addition, we can also use template alias (template alias) to solve this problem. Template aliases can provide a new name for a template, which is convenient for us to use in the program. For example, in the above code, the template alias can be defined like this:
template<typename T> using MyNewClass = MyClass<T>; class MyDerivedClass: public MyNewClass<int> { //... };
In this way, a class can be derived from a template alias.
Summary
In C, using templates is a very common practice, but when using templates to instantiate types in derived classes, it is easy to encounter the compiler error "Derived from templates not allowed" instantiated type" problem. There are two solutions: one is to use template parameters to specify the class to be derived, and the other is to use a template alias to provide a new name for the template. Through the above methods, we can easily solve this problem.
The above is the detailed content of C++ error: Derived from template instantiation type is not allowed, how to solve it?. For more information, please follow other related articles on the PHP Chinese website!